首页 > 解决方案 > 为什么 JS map() 返回 TypeError?

问题描述

在这段简化的代码中,我将一个包含两个属性的对象传递给函数normalize

function normalize() {  
  console.log(this.coords.map(n => n / this.length));  
}

normalize({coords: [0, 2, 3], length: 5});

// OUTPUT: Uncaught TypeError: Cannot read property 'map' of undefined

它抛出一个类型错误。

另一方面,通过不在调用函数中传递对象,它可以工作:

    function normalize() {  
      console.log(obj.coords.map(n => n / obj.length));  
    }

    obj = {
        coords: [0, 2, 3],
        length: 5
    }

    normalize();
    // OUTPUT: [0, 0.4, 0.6]

每个MDN map()需要一个调用数组才能正确执行,并且coords, 在两个示例中似乎都正确传递(作为数组)。

为什么会这样?第一个代码片段有什么问题?

标签: javascriptfunction

解决方案


由于您将数据作为参数传递,因此您希望使用参数而不是使用this.

如此this.coords成为obj.coordsthis.length成为obj.length

function normalize(obj) {
  console.log(obj.coords.map(n => n / obj.length));
}

normalize({
  coords: [0, 2, 3],
  length: 5
});

如果您想使用它,那么您必须将函数制作成这样的原型,然后您不会将项目作为参数传递(通常不建议制作这样的原型):

Object.prototype.normalize = function() {
  return this.coords.map(n => n / this.length);
}

console.log({
  coords: [0, 2, 3],
  length: 5
}.normalize());


推荐阅读