forEach on map function js断言测试未运行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了forEach on map function js断言测试未运行相关的知识,希望对你有一定的参考价值。

我目前正在为map / cubeAll函数进行断言测试。我已经多次修改了我的逻辑和语法,并且我无法发现为什么编译器抛出“类型错误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

谢谢!

答案

函数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');

以上是关于forEach on map function js断言测试未运行的主要内容,如果未能解决你的问题,请参考以下文章

[转] 对 forEach(),map(),filter(),reduce(),find(),every(),some()的理解

JavaScript的map循环forEach循环filter循环

js函数总结

如何形象地解释 JavaScript 中 map,foreach,reduce 间的区别

数组方法重写:forEach, map, filter

前端forEach在Arraymapset中的使用