Javascript 未捕获类型错误:data.push不是函数
我在努力推Javascript 未捕获类型错误:data.push不是函数,javascript,jquery,json,Javascript,Jquery,Json,我在努力推 data.push({"country": "IN"}); 作为json字符串的新id和值。但它给出了以下错误 Uncaught TypeError: data.push is not a function data{"name":"ananta","age":"15"} 提前感谢您的回复您的数据变量包含一个对象,而不是数组,并且对象没有错误状态下的推送功能。要做您需要的事情,您可以这样做: data.country = 'IN'; 或 仅当对象是数组时,才能使用“推送”方法
data.push({"country": "IN"});
作为json字符串的新id和值。但它给出了以下错误
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
提前感谢您的回复您的
数据
变量包含一个对象,而不是数组,并且对象没有错误状态下的推送功能。要做您需要的事情,您可以这样做:
data.country = 'IN';
或
仅当对象是数组时,才能使用“推送”方法:
var data = new Array();
data.push({"country": "IN"}).
或
如果它只是一个你可以使用的对象
data.country = "IN";
要使用数组的push函数,var必须是数组
将数据{“name”:“ananta”,“age”:“15”}
更改为以下内容:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
包含的数组项将是typeof Object,您可以执行以下操作:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
var text=“您是”+data[0]->age+”岁,来自”+data[0]->国家代码>
注意:尽量保持一致。在我的示例中,一个数组包含对象属性name
和age
,而另一个数组只包含country
。如果我用for
或forEach
重复这个过程,那么我就不能总是检查一个属性,因为我的示例中包含了不断变化的项
完美的是:data.push({“name”:“Max”,“age”:“5”,“country”:“Anywhere”})代码>
因此,即使属性为空、null或未定义,您也可以迭代并始终获取属性
编辑
要知道的很酷的东西:
var array = new Array();
类似于:
var array = [];
var object = {};
此外:
类似于:
var array = [];
var object = {};
您还可以将它们组合在一起:
var objectArray = [{}, {}, {}];
尝试以下代码$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);
确保只将推入数组中
如果他们的错误像未捕获类型错误:data.push不是一个函数**
然后检查数据的类型
您可以通过控制台日志(数据)
希望这将有助于同时确保变量的名称不是某种语言关键字。
例如,以下情况会产生相同类型的错误:
var history = [];
history.push("what a mess");
将其替换为:
var history123 = [];
history123.push("pray for a better language");
工作正常。我想您已将其设置为
var data = [];
但过了一段时间,你就这样做了:
data = 'some thing which is not an array';
然后
data.push(“”)
将不起作用,因为它不再是数组。请记住,push只对数组[]起作用,而不是对象{}
如果要在n中添加类似对象o
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);
因为数据
不是数组
。如果它是一个对象
,只需将date.country='IN'
。如果是“JSON字符串”,最好先反序列化它。data.country='IN'
确保不要执行“data=data.push(…)”。这也会导致前面提到的错误。假设我将country作为变量,并且我想传递变量值,那么我如何实现这样的效果呢?@HarshPatel使用括号表示法的第二个示例可以处理变量:var propertyName='country';数据[propertyName]='IN'代码>