我想推
data.push({"country": "IN"});
作为json字符串的新id和值。但它会出现以下错误
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
预先感谢您的回复
要使用Array的push函数,var必须是一个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"});
..
包含的Array项将是typeof Object,您可以执行以下操作:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
注意:尽量保持一致。在我的例子中,一个数组包含对象属性name
和age
,而另一个数组包含country
。如果我用for
或forEach
迭代它,那么我不能总是检查一个属性,因为我的例子包含改变的项目。
完美将是:data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
因此,您可以迭代并始终获取属性,即使它们为空,null或未定义。
编辑
很酷的东西要知道:
var array = new Array();
类似于:
var array = [];
也:
var object = new Object();
类似于:
var object = {};
你也可以把它们结合起来:
var objectArray = [{}, {}, {}];
您的data
变量包含一个对象,而不是一个数组,并且对象没有push
函数作为错误状态。要做你需要的,你可以这样做:
data.country = 'IN';
要么
data['country'] = 'IN';
只有当对象是一个数组时才能使用push方法:
var data = new Array();
data.push({"country": "IN"}).
要么
data['country'] = "IN"
如果它只是一个你可以使用的对象
data.country = "IN";
还要确保变量的名称不是某种语言关键字。例如,以下内容产生相同类型的错误:
var history = [];
history.push("what a mess");
替换它:
var history123 = [];
history123.push("pray for a better language");
按预期工作。
试试这个代码$ scope.DSRListGrid.data = 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);
确保你只是推入一个数组,如果他们的错误像Uncaught TypeError:data.push不是一个函数**然后检查你可以通过consol.log(数据)做的数据类型希望这将有所帮助
我想你定了
var data = [];
但经过一段时间你做到了
data = 'some things';
然后data.push('')
不工作。