在地图功能上进行foreach js断言测试未运行



我当前正在为MAP/CUBEALL功能进行断言测试。我已经多次修改了逻辑和语法,我还没有发现编译器为何投掷"类型错误数组。我已经阅读了有关TypeError错误的MDN页面,并且我知道我的" foreach"试图从函数和array.protype.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

谢谢!

功能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');

最新更新