Uncaught TypeError: data.push is not a function

前端 未结 8 1465
半阙折子戏
半阙折子戏 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-05 00:12

    To use the push function of an Array your var needs to be an Array.

    Change data{"name":"ananta","age":"15"} to following:

    var data = [
        { 
            "name": "ananta",
            "age": "15",
            "country": "Atlanta"
        }
    ];
    
    data.push({"name": "Tony Montana", "age": "99"});
    
    data.push({"country": "IN"});
    
    ..
    

    The containing Array Items will be typeof Object and you can do following:

    var text = "You are " + data[0]->age + " old and come from " + data[0]->country;

    Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.

    Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );

    So you can iterate and always can get the properties, even if they are empty, null or undefined.

    edit

    Cool stuff to know:

    var array = new Array();
    

    is similar to:

    var array = [];
    

    Also:

    var object = new Object();
    

    is similar to:

    var object = {};
    

    You also can combine them:

    var objectArray = [{}, {}, {}];
    
    0 讨论(0)
  • 2020-12-05 00:15

    one things to remember push work only with array[] not object{}.

    if you want to add Like object o inside inside n

    
    
    a={ b:"c",
    D:"e",
    F: {g:"h",
    I:"j",
    k:{ l:"m"
    }}
    }
    
    a.F.k.n = { o: "p" };
    a.F.k.n = { o: "p" };
    console.log(a);
    0 讨论(0)
提交回复
热议问题