假设我们有这个 JSON:
{ "A" : {"A1": "1" } }
如何提取实际索引 A1 ?这样我就可以在 JS 中使用它,例如:
var index = "A1";
假设我们有这个 JSON:
{ "A" : {"A1": "1" } }
如何提取实际索引 A1 ?这样我就可以在 JS 中使用它,例如:
var index = "A1";
编辑——如果你的意思是“我如何提取索引 A1 处的值”,那么你只需使用点或括号运算符:
var value = object.A.A1;
或者
var index = "A1";
var value = object.A[index];
其他见下文。
您可以使用循环遍历对象的属性名称for ... in:
for (var propertyName in object) {
// ...
}
该循环还将包括原型链中的属性,因此您可以使用名为 的函数来避免这种情况(如果需要)hasOwnProperty:
for (var name in object) {
if (object.hasOwnProperty(name)) {
// really is a local property
}
}
较新的浏览器支持一种将属性名称作为数组获取的方法:
var names = Object.keys( yourObject );
该列表将仅包括“自己的”属性;也就是说,那些hasOwnProperty()会返回true的。
Finally, there are ways that properties can be defined such that they're not "enumerable". Usually when that's done, you would generally not want to see them in for ... in anyway.