我有这个练习,我需要帮助了解我哪里出错了。到目前为止,这是我的代码。
// Exercise Two: In this exercise you will be given an array called 'cents'
// This array is a list of prices, but everything is in cents instead of dollars.
// Using the map method, divide every value by 100 and save it as a new array 'dollars'
function exerciseTwo(cents){
function mapMethod(array, cb) { // created the map method
let dollars = []; // declaring the new array 'dollars'
for (i=0; i < array.length; i++) { //iterating through the loop
let updatedValue = cb(array[i] / 100); // dividing the iteration by 100
dollars.push(updatedValue); //pushing the updated value to the new array 'dollars'
}
return dollars;
}
// Please write your answer in the lines above.
return dollars; // getting error that 'dollars' is not defined :(
}
我认为你应该区分声明和调用函数。
function square(x) {
return x*x;
} // <-- This is declare
square(3) // <-- This is call
你在上面的代码中所做的只是在mapMethod
函数中声明一个exerciseTwo
函数,它将在系统运行测试时被调用。但是你的mapMethod
函数不会被调用,只是定义了。
内部函数可以使用外部函数的变量,但反之亦然。然后你不能从外部函数dollars
返回在内部函数mapMethod()
中声明的exerciseTwo()
遵循要求。您应该使用map方法简化代码。
function exerciseTwo(cents){
const dollars = cents.map(cent => cent/100)
return dollars
}
- 你有这个错误,因为你试图返还美元并且主函数上不存在美元,这是无效的:
let updatedValue = cb(array[i] / 100);
做这个:
let updatedValue = cb(cents[i] / 100);
但你没有看到美分,因为你没有在函数内声明它
以下是作者编写的首选代码。显然有更多“给猫皮肤的方法”。
const dollars = cents.map(function(price){
return price/100;