[英]find largest id within array object using $.each
[{"id":1},{"id":2},{"id":3}]
我知道我可以使用max這樣的var max = Math.max.apply(Math,myArray)(如果我有這樣的數組[1,2,3]
)但是因為我必須遍歷列表,所以我只是想知道我可以使用循環來獲得最大的數字;
$.each(function(){
//this.id
// how to continue here?
});
您仍然可以使用Math.max.apply
構造。 只需使用map
從對象中生成一組id:
var maxId = Math.max.apply(Math, myList.map(function(o){ return o.id }));
var items = [{ "id": 2 }, { "id": 1 }, { "id": 3 }];
var maxId = Number.MIN_VALUE;
$.each(items, function (index, item) {
maxId = Math.max(maxId, item.id);
});
var maxId = Number.MIN_VALUE;
items.forEach(function (item) {
maxId = Math.max(maxId, item.id)
});
var maxId = items.reduce(function (maxId, item) {
return Math.max(maxId, item.id)
}, Number.MIN_VALUE);
Underscore.js的max也適用於舊瀏覽器:
var maxId = _.max(items, function (item) { return item.id }).id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.