未捕获的TypeError:data.push不是函数 [英] Uncaught TypeError: data.push is not a function
问题描述
我正在尝试
data.push({"country": "IN"});
作为json字符串的新ID和值.但它给出了以下错误
as new id and value to a json string. but it gives the following error
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
高级谢谢您的答复
推荐答案
要使用Array的push函数,您的var必须是一个Array.
To use the push function of an Array your var needs to be an Array.
将data{"name":"ananta","age":"15"}
更改为以下内容:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
包含的数组项将是typeof对象,您可以执行以下操作:
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;
注意:请保持一致.在我的示例中,一个数组包含对象属性name
和age
,而另一个仅包含country
.如果我用for
或forEach
进行迭代,那么我就不能总是检查一个属性,因为我的示例包含了变化的项目.
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.
完美将是:data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
因此,您可以迭代并始终获得属性,即使它们为空,null或未定义.
So you can iterate and always can get the properties, even if they are empty, null or undefined.
编辑
要知道的很酷的东西:
var array = new Array();
类似于:
var array = [];
也:
var object = new Object();
类似于:
var object = {};
您也可以将它们组合在一起:
You also can combine them:
var objectArray = [{}, {}, {}];
这篇关于未捕获的TypeError:data.push不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!