javascript - TypeError: this.reduce 不是一个函数

标签 javascript arrays prototype typeerror reduce

<分区>

将方法添加到 Array 原型(prototype)后,其他一些不相关的脚本中断。

  • [Opera] 未处理的错误:“this.reduce”不是一个函数
  • [Firefox] TypeError: this.reduce 不是一个函数

该方法本身有效([1,2,3].xintsum() 按预期输出 6)。

// adding a function to the Array prototype
Array.prototype.xintsum = function() { return this.reduce(function(old, add) {return old + add;}, 0); };

// accessing the array in a way that worked before
$(document).ready(function (){
  var some_array = [];
  for (head_n in some_array) {
    var v = some_array[head_n];
    $('<th></th>').text(v);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最佳答案

发生这种情况是因为您在数组上使用了 for..in。你不应该那样做。

当您添加 Array.prototype.xintsum 时,您向每个 数组添加了一个xintsum 属性。所以,发生的事情是,您的 for 循环迭代了数组的该属性。

这个属性的值是一个函数。当您将函数传递给 .text() 时,jQuery 会这样调用它:

v.call(ele, index text);

它正在为元素设置 this。而且,DOMElement 没有 .reduce 函数。

你需要像这样循环:

for(var i = 0; i < some_array.length; i++){
    var v = some_array[i];
}

关于javascript - TypeError: this.reduce 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21121830/

相关文章:

JavaScript/jQuery 组合具有相同优先级的数字

php - 从 2 个数据库查询和 2 个循环加载多维数组

prototype - 在 Mojo 框架 (WebOS) 中启动和停止监听器

javascript - 如何在 React 中使用钩子(Hook)绑定(bind)函数?

javascript - Jquery 使用 .button() 时未设置元素 ID

javascript - JS 遍历对象并检查另一个对象是否包含其值

javascript - js从不同脚本的原型(prototype)触发事件

javascript - wavesurfer.js play([start[, end]]) end 不起作用

javascript - 如何在浏览器中使用 npm 安装的 cesium

javascript - hasOwnProperty 与 propertyIsEnumerable