javascript - 为什么 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
, 在两个示例中似乎都正确传递(作为数组)。
为什么会这样?第一个代码片段有什么问题?
解决方案
由于您将数据作为参数传递,因此您希望使用参数而不是使用this
.
如此this.coords
成为obj.coords
和this.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());
推荐阅读
- java - 登录时谷歌玩游戏 API 错误 12501
- jquery - 如何使用 Selenium 和 java 自动化 jquery 选择的下拉列表
- dask - dask.distributed 未使用集群
- swift - macOS 上的 EnvironmentObject 和 SceneDelegate
- android - 如何将壁纸设置为锁屏或两者(家庭和锁定)?
- angular - Ionic 3:离子列表未显示在离子项目内
- class - 鼠标释放后填充的矩形消失
- javascript - 在 for 循环中调用函数 - JavaScirpt
- java - 我为家庭作业编写了一些代码,但我不相信它有效。这是约瑟夫斯问题的代码
- python - 那时我应该在 Python 中做什么?