在JavaScript中读取JSON编码的数组 [英] Reading a json encoded array in javascript
问题描述
此php函数通过ajax将json编码的对象返回给javascript.我使用带有stringify的json对象创建了一个变量.
This php function returns a json encoded object to a javascript through ajax. I create a variable with this json object with stringify.
var event_id = JSON.stringify(rdata.event_id);
当我打印该变量时,它看起来像这样.
When I print that variable it looks like this.
[{"0":"e20111129215359"},{"0":"e20120301133826"},{"0":"e20120301184354"},{"0":"e20120301193226"},{"0":"e20120301193505"},{"0":"e20120303182807"},{"0":"e20120303205512"},{"0":"e20120303211019"},{"0":"e20120306182514"},{"0":"e20120307122044"}]
如何访问event_id的每个元素?
How do I access each element of event_id?
推荐答案
不要stringify
它.它已经是一个有效的JavaScript对象,因此只需使用以下命令即可直接访问它:
Don't stringify
it. It's already a valid JavaScript object, so just access it directly with:
rdata.event_id[0]["0"];
// e20111129215359
// Or read them in a loop
for (var i=0; i<rdata.event_id.length; i++) {
console.log(rdata.event_id[i]["0"];
}
值rdata.event_id
是一个数组[]
,其中包含一堆对象常量{}
,每个对象常量仅具有一个属性"0"
.由于该属性是数字而不是字符串,因此您需要使用["0"]
语法而不是普通的对象点运算符来访问它.
The value rdata.event_id
is an array []
containing a bunch of object literals {}
each having just one property "0"
. Since the property is a number instead of a string, you need to use the ["0"]
syntax to access it, rather than the normal object dot operator.
这篇关于在JavaScript中读取JSON编码的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!