javascript - 获得意外的输出
问题描述
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,无穷大,无穷大]
有人可以解释错误吗?
解决方案
您需要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 }));
推荐阅读
- c++ - std::async 和 std::future 在后台使用互斥锁和条件变量吗?
- visual-studio-code - 权限被拒绝在 Visual Studio Code 中构建 CPP 文件
- gitlab - 如果目录中有 Gemfile,则 Gitlab-runner 失败
- python - Snakemake - 使用 sftp 下载数据的规则
- react-native - 如何在 react-native 中输入文本输入时获得建议
- java - Kotlin 中运行时 Json 处理程序包装器的实际类类型
- django - 是否有允许管理员按字段值对模型对象进行排序的 django 管理小部件?
- c++ - 为什么变量和函数不能同名?
- python - 如何检查字符串是否包含字符和空格(空字符)?
- reactjs - 通过 React useEffect 方法对数组中的 obj 进行排序