Question

After adding a method to the Array prototype, some other, unrelated script breaks.

  • [Opera] Unhandled Error: 'this.reduce' is not a function
  • [Firefox] TypeError: this.reduce is not a function

The method itself works ([1,2,3].xintsum() outputs 6 as expected).

// 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>

Was it helpful?

Solution

This is happening because you are using for..in on an array. You shouldn't be doing that.

When you added Array.prototype.xintsum, you added a xintsum property to every array. So, what happened was, that your for loop iterated over that property of your array.

The value of this property is a function. When you pass a function to .text(), jQuery will call it like this:

v.call(ele, index text);

It's setting this to the element. And well, DOMElements don't have .reduce functions.

You need to loop like this:

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

OTHER TIPS

This code:

var v = some_array[head_n];
$('<th></th>').text(v);

when it gets to xintsum is the same as this:

$('<th></th>').text(function() { 
    return this.reduce(function(old, add) {
        return old + add;
    }, 0); 
});

When a function is passed to text, the function is called once for each element contained in the jquery object which it is called on. For each call this refers to that dom element. In this case, the th you have created. Therefore, the error message is letting you know that th has no such function.

v() is being called in the context of the <th> element, not an array. Hence, the <th> doesn't have a method reduce(). This is because for ... in iterates over non-numeric properties just as much as numeric properties. I would recommend using some_array['head'].forEach() instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top