Cannot read property 'push' of undefined when combining arrays

前端 未结 8 2031
轮回少年
轮回少年 2021-02-01 12:18

When pushing an array\'s contents to another array I get

\"Uncaught TypeError: Cannot read property \'push\' of undefined\" error in this snippet.

相关标签:
8条回答
  • 2021-02-01 12:52

    You do not need to give an index.

    Instead of doing order[0].push(a[i]), just do order.push(a[i]).

    0 讨论(0)
  • 2021-02-01 12:55

    You get the error because order[1] is undefined.

    That error message means that somewhere in your code, an attempt is being made to access a property with some name (here it's "push"), but instead of an object, the base for the reference is actually undefined. Thus, to find the problem, you'd look for code that refers to that property name ("push"), and see what's to the left of it. In this case, the code is

    if(parseInt(a[i].daysleft) > 0){ order[1].push(a[i]); }
    

    which means that the code expects order[1] to be an array. It is, however, not an array; it's undefined, so you get the error. Why is it undefined? Well, your code doesn't do anything to make it anything else, based on what's in your question.

    Now, if you just want to place a[i] in a particular property of the object, then there's no need to call .push() at all:

    var order = [], stack = [];
    for(var i=0;i<a.length;i++){
        if(parseInt(a[i].daysleft) == 0){ order[0] = a[i]; }
        if(parseInt(a[i].daysleft) > 0){ order[1] = a[i]; }
        if(parseInt(a[i].daysleft) < 0){ order[2] = a[i]; }
    }
    
    0 讨论(0)
提交回复
热议问题