javascript 未捕获的类型错误:无法读取简单 JSON 数组的未定义属性“长度”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23935666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'length' of undefined for simple JSON array
提问by victorvictord
I am calling a function this way .
我正在以这种方式调用函数。
var responseinner = returnvalues(selectedeleemnt);
console.log(responseinner);
displaying as Object
显示为对象
console.log(JSON.stringify(responseinner));
displaying as[{"name":"Coke","image":"json_images/coke_can.jpg","type":["250ml","300ml"],"price":["50","60"]}]
显示为[{"name":"Coke","image":"json_images/coke_can.jpg","type":["250ml","300ml"],"price":["50","60"]}]
I tried all the ways of parsing this value
我尝试了所有解析这个值的方法
[{"name":"Coke","image":"json_images/coke_can.jpg","type":["250ml","300ml"],"price":["50","60"]}]
But always it throws the error as
但它总是抛出错误
Uncaught TypeError: Cannot read property 'length' of undefined
未捕获的类型错误:无法读取未定义的属性“长度”
I used JSON.parse , JSON.stringfy() . but none helped .
我使用了 JSON.parse , JSON.stringfy() 。但没有帮助。
for (var i = 0; i < responseinner.type.length; i++) {
}
could anybody please help me
有人可以帮我吗
回答by victorvictord
for(var i=0;i<responseinner.length;i++){
responseinner[i].type .... }
for(var i=0;i<responseinner.length;i++){
responseinner[i].type .... }
回答by Amit Joki
Your responseinner
isn't an Object
but an Array
with only one element.
你responseinner
不是一个,Object
而是一个Array
只有一个元素。
So, you'll have to use responseinner[0].type.length
所以,你必须使用 responseinner[0].type.length
If it was an object, it would have started with {}
and not []
, with what arrays start.
如果它是一个对象,它将以数组开头{}
而不是[]
开头。
回答by Aboca
To parse json with jquery:
使用 jquery 解析 json:
$.each($.parseJSON(responseinner), function(key,value){
//do something
});
If responseinner is already formed as a json you don't need the $.parseJSON
如果 responseinner 已经形成为一个 json 你不需要 $.parseJSON
or
或者
responseineer[0].name
responseineer[0].image
...
Json data comes into an array so get it's object with an index, so to access it: responseineer[0]
Json 数据进入一个数组,因此使用索引获取它的对象,以便访问它: responseineer[0]
回答by theClap
try test[0].type.length
you have an Object in an array of length 1 therefore you must first define the index location of the Object in the array which is trivial since the array has 1 defined index.
尝试test[0].type.length
在长度为 1 的数组中有一个对象,因此您必须首先在数组中定义对象的索引位置,这是微不足道的,因为数组有 1 个定义的索引。
for (var i = 0; i < responseinner[0].type.length; i++) {
}
回答by Vinoth Narayan
for(var i=0;i
for(var i=0;i
Its works fine but...how to assign to gridview in client side
它工作正常但是......如何在客户端分配给gridview