我有这个数组:
var arr = []; arr.push({name:"k1", value:"abc"}); arr.push({name:"k2", value:"hi"}); arr.push({name:"k3", value:"oa"});
是否可以通过知道名称来获取值或特定元素?
像这样的东西:
arr['k2'].value
要么
arr.get('k1')
通常通过数字索引访问数组,因此在您的示例中arr[0] == {name:"k1", value:"abc"}。如果您知道name每个对象的属性都是唯一的,则可以将它们存储在对象而不是数组中,如下所示:
arr[0] == {name:"k1", value:"abc"}
name
var obj = {}; obj["k1"] = "abc"; obj["k2"] = "hi"; obj["k3"] = "oa"; alert(obj["k2"]); // displays "hi"
如果您实际上想要一个像您的帖子中那样的对象数组,则可以遍历该数组并在找到具有对象具有所需属性的元素时返回:
function findElement(arr, propName, propValue) { for (var i=0; i < arr.length; i++) if (arr[i][propName] == propValue) return arr[i]; // will return undefined if not found; you could return a default instead } // Using the array from the question var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"} alert(x["value"]); // displays "hi" var y = findElement(arr, "name", "k9"); // y is undefined alert(y["value"]); // error because y is undefined alert(findElement(arr, "name", "k2")["value"]); // displays "hi"; alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property