【问题标题】:find largest id within array object using $.each使用 $.each 在数组对象中查找最大 id
【发布时间】:2015-08-02 10:01:32
【问题描述】:
[{"id":1},{"id":2},{"id":3}]

我知道我可以像这样使用 max var large = Math.max.apply(Math, myArray) (如果我有这样的数组 [1,2,3])但是因为我必须遍历一个列表,我只是想知道我可以使用循环获取最大数;

$.each(function(){
//this.id
// how to continue here?
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您仍然可以使用Math.max.apply 构造。只需使用 map 从对象中创建一个 id 数组:

    var maxId = Math.max.apply(Math, myList.map(function(o){ return o.id }));
    

    【讨论】:

      【解决方案2】:

      使用 $.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;
      

      【讨论】:

      • 为什么不使用 $.each?
      • 如果您只支持现代浏览器,原生 JavaScript 函数(如 map、forEach 和 reduce)更可取。
      猜你喜欢
      • 2014-05-07
      • 2020-05-04
      • 1970-01-01
      • 2018-04-05
      • 2022-01-18
      相关资源
      最近更新 更多