Skip to content Skip to sidebar Skip to footer

Javascript Error 'has No Method Push'

I'm getting the error: object 0 has no method 'push', and I can't figure out why. I know that sack[i] is the object, i is 0 and quantity_to_spawn equals 1. I think that node has a

Solution 1:

I'm sure you are missing to declare the variable sack as an array,

var sack = newArray();

or

var sack = [];

Otherwise it should work

Here is the simple demo

I made some experiment regard to this problem, found some interesting facts. Those are,

The problem is sack is already assigned something like var sack = 'someValue';. in this case (assigned value string type), this resulting in sack to be a string array. Hence the assignment sack[i]=new Array(); make no sense. sack[0] will be s. and try to push some value to this will throw the error object 0 has no method 'push'

Another case(assigned value number type), assignment is like var sack = 28892;. In this case, the same array assignment making no sense. But if you try to push something to sack[0] it will throw Cannot call method 'push' of undefined, since sack[0] is undefined.

In both cases, after declaring sack to some value, the assignment not produced any error, though it is useless.

Additional information about array declaration,

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Solution 2:

No idea what you are doing here, but try this:

var sack = [];
for (var i=0;i<rows[r].quantity_to_spawn;i++) {
  var more_drops = Math.random();
  sack[i] = [];
  for (;more_drops > 0.05;) {
      more_drops = Math.random();
      var rarity = Math.random();
      if (rarity <= 0.75&&typeof rows[r].common==="string") {//common drop 75%var item = rows[r].common.split(",");
         sack[i].push(parseInt(item[parseInt(Math.random()*item.length,10)],10));
         ... 

Post a Comment for "Javascript Error 'has No Method Push'"