当使用Javascript迭代JSON for … in时,返回的最终键是“remove”

When iterating JSON with Javascript for…in, the final key returned is “remove”

本问题已经有最佳答案,请猛点这里访问。

这确实是一个奇怪的事件。首先,我使用的是Chrome23.x版本,但还没有在其他浏览器中重现。

我从表单的服务器接收到一个JSON数组:

杰森

1
2
3
4
5
6
7
8
9
10
11
{
"layout":0,
"caption":"Work History",
"cols":[
   {"field":"company","label":"Company Name","hidden":false,"order":-1,"validationType":2,"list":[]},       {"field":"date_start","label":"From","hidden":false,"order":-1,"validationType":1,"list":[]},
   {"field":"date_end","label":"Until","hidden":false,"order":-1,"validationType":0,"list":[]},
   {"field":"position","label":"Title","hidden":false,"order":-1,"validationType":2,"list":[]},
   {"field":"description","label":"Description","hidden":false,"order":-1,"validationType":0,"list":[]},
   {"field":"project","label":"Project","hidden":false,"order":-1,"validationType":64,"list":[]}
   ]
}

然后,我尝试用javascript循环Cols对象。"

JavaScript

1
2
3
for (var c in json.cols) {
    console.log("col name:" + c);
}

Google Chrome的控制台打印以下内容:

产量

1
2
3
4
5
6
7
col name: 0
col name: 1
col name: 2
col name: 3
col name: 4
col name: 5
col name: remove

首先,应该只有6个输出。第二,这个最后的"删除"键是从哪里来的?为什么要列出?


使用if( json.cols.hasOwnProperty(c) ) { ... }将代码包装在for…in循环中。

从MDN获取:

If you only want to consider properties attached to the object itself,
and not its prototypes, use getOwnPropertyNames or perform a
hasOwnProperty check (propertyIsEnumerable can also be used).

A for...in loop iterates over the properties of an object in an
arbitrary order

JavaScript:

1
2
3
4
5
for (var c in json.cols) {
    if( json.cols.hasOwnProperty(c) ) {
      console.log("col name:" + c);
    }
}

例子


您的obj.json.cols实际上是一个数组,而不是一个对象,因此您应该使用for(;;)循环对其进行迭代。我相信你在找这样的东西:

1
2
3
for (var i=0; i<json.cols.length; i++) {
    console.log("col name:" + json.cols[i].label);
}

此外,在您的网页上,似乎有一些脚本与Array.prototype混淆,就像在for..in循环中,您不应该看到remove属性。