我有几个id和高度的数组。
如何获得特定身份证的高度?
喜欢从数组中获取review-1的值吗?这是“500px”?
感谢。
ar=[];
ar.push({"id":"reiew-1","height":"500px"});
$.each(ar,function(index,value){
alert(value.height); // gets all the heights
});
答案 0 :(得分:1)
在循环中使用if条件
ar = [];
ar.push({
"id": "reiew-1",
"height": "500px"
});
$.each(ar, function (index, value) {
if (value.id == 'reiew-1') {
alert(value.height); // gets all the heights
return false;//stop further looping of the array since the value you are looking for is found
}
});
答案 1 :(得分:1)
所以你只能使用javascript方法来做这件事
var ar=[];
ar.push({"id":"reiew-1","height":"500px"}, {"id":"reiew-3","height":"500px"});
// function that filter and return object with selected id
function getById(array, id){
return array.filter(function(item){
return item.id == id;
})[0].height || null;
}
// now you can use this method
console.log(getById(ar, "reiew-1"))
您可以使用此代码demo
答案 2 :(得分:0)
你可以去functional
做类似的事情:
ar=[
{"id":"reiew-1","height":"500px"},
{"id":"reiew-2","height":"600px"},
{"id":"reiew-3","height":"700px"},
];
filterById=function(value){
return function(o){
return o["id"]===value;
};
}
getAttribute=function(value){
return function(o){
return o[value];
}
}
ar.filter(filterById("reiew-1")).map(getAttribute("height"))
眼睛很容易:]
以下是fiddle
有关更多信息(例如有关浏览器兼容性),以下是MDN链接:Array.prototype.filter()
和Array.prototype.map()