我目前正在为map/ cubeAll函数进行断言测试。我已经多次修改了我的逻辑和语法,我还没有发现为什么编译器会抛出一个"Type array.forEach不是一个函数“错误。我读过关于TypeError错误的MDN页面,我知道我的“forEach”试图从一个函数调用一个值,并且Array.prototype.forEach需要一个回调函数才能正常工作。根据我的逻辑,在我的代码(下面)中,我确实有一个回调函数,并且我试图通过将数组中的每个元素传递回这个调用来调用一个值。怎么啦?
function map(array, callbackFunction) {
var newArray = [];
array.forEach(function(element) {
newArray.push(callbackFunction(element));
});
return newArray;
}
function cubeAll(numbers) {
return map(numbers, function(n) {
return n * n * n;
});
}
function assertArraysEqual(actual, expected, testName) {
let arraysHaveEqualLength = actual.length === expected.length;
let arraysHaveSameElements = actual.every(function(ele,idx){
return ele === expected[idx];
});
if(arraysHaveEqualLength && arraysHaveSameElements){
console.log(`${testName} has passed.`);
}else {
console.log(`${testName} has FAILED. Expected ${expected} and got ${actual} instead.`);
}
}我试着测试的案例:
assertArraysEqual(map([3,2,1],cubeAll),[27,8,1], 'it should return a new array with all the elements cubed');
assertArraysEqual(map([3,2,1],cubeAll),[27,7,1], 'it should return a new array with all the elements cubed');控制台中的错误:
array.forEach(element => newArray.push(callbackFunction(element)));
^
TypeError: array.forEach is not a function谢谢!
发布于 2018-02-28 20:15:22
函数cubeAll接收一个数字而不是一个数组。
function cubeAll(n) {
return n * n * n;
}您可以使用内置对象Math和函数.pow(...)。
return Math.pow(n, 3);对于支持ES2016的环境(常绿浏览器,节点7+)
function cubeAll(n) {
return n ** 3;
}
function map(array, callbackFunction) {
var newArray = [];
array.forEach(function(element) {
newArray.push(callbackFunction(element));
});
return newArray;
}
function cubeAll(n) {
return n ** 3;
}
function assertArraysEqual(actual, expected, testName) {
let arraysHaveEqualLength = actual.length === expected.length;
let arraysHaveSameElements = actual.every(function(ele,idx){
return ele === expected[idx];
});
if(arraysHaveEqualLength && arraysHaveSameElements){
console.log(`${testName} has passed.`);
}else {
console.log(`${testName} has FAILED. Expected ${expected} and got ${actual} instead.`);
}
}
assertArraysEqual(map([3,2,1],cubeAll),[27,8,1], 'it should return a new array with all the elements cubed');
assertArraysEqual(map([3,2,1],cubeAll),[27,7,1], 'it should return a new array with all the elements cubed');
https://stackoverflow.com/questions/49037733
复制相似问题