簡體   English   中英

使用$ .each在數組對象中找到最大的id

[英]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 }));

使用$ .each

var items = [{ "id": 2 }, { "id": 1 }, { "id": 3 }];

var maxId = Number.MIN_VALUE;
$.each(items, function (index, item) {
    maxId = Math.max(maxId, item.id);
});

使用ES5 forEach

var maxId = Number.MIN_VALUE;
items.forEach(function (item) {
    maxId = Math.max(maxId, item.id)
});

使用ES5減少

var maxId = items.reduce(function (maxId, item) {
    return Math.max(maxId, item.id)
}, Number.MIN_VALUE);

使用Underscore.js

Underscore.js的max也適用於舊瀏覽器:

var maxId = _.max(items, function (item) { return item.id }).id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM