16 javascript arrays reduce prototype typeerror
在向 Array 原型添加方法后,其他一些不相关的脚本会中断。
该方法本身有效(按预期[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);
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为您正在for..in数组上使用。你不应该这样做。
当您添加 时Array.prototype.xintsum,您xintsum向每个数组添加了一个属性。所以,发生的事情是,您的for循环迭代了数组的该属性。
该属性的值是一个函数。当你将一个函数传递给 时.text(),jQuery 将像这样调用它:
v.call(ele, index text);
Run Code Online (Sandbox Code Playgroud)
它正在设置this为元素。而且,DOMElement 没有.reduce函数。
你需要像这样循环:
for(var i = 0; i < some_array.length; i++){
var v = some_array[i];
}
Run Code Online (Sandbox Code Playgroud)