关于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()分开执行时不会报错,一起执行时也会报同样的错,这是什么原因

已解决 悬赏分:10 - 解决时间 2021-11-26 11:41
反对 0举报 0 收藏 0

回答2

最佳
  • @

    目测是分号问题!!!

    Array.prototype.distinct = function () {
       .....
    };
    [1,2,3,3,4,4].distinct()
    支持 0 反对 0 举报
    2021-11-26 06:20
  • @

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

    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();
    支持 0 反对 0 举报
    2021-11-26 06:26