关于JavaScript在Array.prototype上添加函数的问题

在Array.prototype上添加函数时,例如

Array.prototype.distinct = function () {
    console.log(this)
    const map = {}
    const result = []
    for (const n of this) {
       if (!(n in map)) {
           map[n] = 1
           result.push(n)
       }
    }
    return result
}
[1,2,3,3,4,4].distinct()

这样执行就会报Uncaught TypeError: Cannot read property 'distinct' of undefined的错误,而把[1,2,3,3,4,4].distinct()换成var a = [1,2,3,3,4,4].distinct()时就不会报错,还有一个奇怪的地方是Array.prototype.distinct定义和[1,2,3,3,4,4].distinct()分开执行时不会报错,一起执行时也会报同样的错,这是什么原因

阅读 2.7k
2 个回答

目测是分号问题!!!

Array.prototype.distinct = function () {
   .....
};
[1,2,3,3,4,4].distinct()

你以为你的代码长那样,其实它长这样。

Array.prototype.distinct = function() {
  console.log(this);
  const map = {};
  const result = [];
  for (const n of this) {
    if (!(n in map)) {
      map[n] = 1;
      result.push(n);
    }
  }
  return result;
}[(1, 2, 3, 3, 4, 4)].distinct();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题