首页 > 解决方案 > 获得意外的输出

问题描述

function normalize() {
   console.log(this.coords.map(function(x){
      return x/this.length;
 }));
}

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

预期输出:[0,0.4,0.6]

输出:[NaN,无穷大,无穷大]

有人可以解释错误吗?

标签: javascriptmaps

解决方案


您需要this使用用于映射的功能Array#map。没有thisArg,回调将无法访问this

function normalize() {
    return this.coords.map(function (x) {
        return x/this.length;
    }, this);
}

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


推荐阅读