Uncaught TypeError: data.push is not a function

前端 未结 8 1464
半阙折子戏
半阙折子戏 2020-12-04 23:45

I am trying to push

data.push({\"country\": \"IN\"});

as new id and value to a json string. but it gives the following error



        
相关标签:
8条回答
  • 2020-12-04 23:51

    make sure you push into an Array only and if their is error like Uncaught TypeError: data.push is not a function** then check for type of data you can do this by consol.log(data) hope this will help

    0 讨论(0)
  • 2020-12-04 23:58

    you can use push method only if the object is an array:

    var data = new Array();
    data.push({"country": "IN"}).
    

    OR

    data['country'] = "IN"
    

    if it's just an object you can use

    data.country = "IN";
    
    0 讨论(0)
  • 2020-12-05 00:03

    Try This Code $scope.DSRListGrid.data = data; this one for source data

                for (var prop in data[0]) {
                    if (data[0].hasOwnProperty(prop)) {
                        $scope.ListColumns.push(
                                {
                                    "name": prop,
                                    "field": prop,
                                    "width": 150,
                                    "headerCellClass": 'font-12'
                                }
                        );
                    }
                }
                console.log($scope.ListColumns);
    
    0 讨论(0)
  • 2020-12-05 00:04

    Your data variable contains an object, not an array, and objects do not have the push function as the error states. To do what you need you can do this:

    data.country = 'IN';
    

    Or

    data['country'] = 'IN';
    
    0 讨论(0)
  • 2020-12-05 00:05

    I think you set it as

    var data = []; 
    

    but after some time you made it like:

    data = 'some thing which is not an array'; 
    

    then data.push('') will not work as it is not an array anymore.

    0 讨论(0)
  • 2020-12-05 00:09

    Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:

    var history = [];
    history.push("what a mess");
    

    replacing it for:

    var history123 = [];
    history123.push("pray for a better language");
    

    works as expected.

    0 讨论(0)
提交回复
热议问题