Get highest id using javascript

喜你入骨 提交于 2021-01-28 04:26:29

问题


I have a bunch of note divs in the following format:

<div class="note-row" id="1">
<div class="note-row" id="2">
<div class="note-row" id="4">
<div class="note-row" id="5">
<div class="note-row" id="6">

How would I get the largest id using javascript? So far I have:

$('.note-row').each(function() {
    ??
});

回答1:


Quick and dirty way:

var max = 0;
$('.note-row').each(function() {
    max = Math.max(this.id, max);
});
console.log(max); 

This is a little shorter and more sophisticated (for using reduce, and also allowing negative ids down to Number.NEGATIVE_INFINITY, as suggested by Blazemonger):

var max = $('.note-row').get().reduce(function(a, b){
    return Math.max(a, b.id)
}, Number.NEGATIVE_INFINITY);



回答2:


You could do something like this:

var ids = $('.note-row').map(function() {
    return parseInt(this.id, 10);
}).get();

var max = Math.max.apply(Math, ids);



回答3:


Funny but this also works:

var max = $('.note-row').sort(function(a, b) { return +a.id < +b.id })[0].id;

http://jsfiddle.net/N5zWe/




回答4:


In the interest of completeness, an optimized Vanilla JS solution:

var n = document.getElementsByClassName('note-row'),
    m = Number.NEGATIVE_INFINITY,
    i = 0,
    j = n.length;
for (;i<j;i++) {
    m = Math.max(n[i].id,m);
}
console.log(m);



回答5:


The same way you'd find any max, loop:

var max = -999; // some really low sentinel

$('.note-row').each(function() {
    var idAsNumber = parseInt(this.id, 10);
    if (idAsNumber  > max) {
        max = idAsNumber;
    }
});



回答6:


  var maxID = -1;
  $('.note-row').each(function() {
       var myid = parseInt($(this).attr('id'),10);
       if( maxID < myid ) maxID = myid;
  });
  // the value of maxID will be the max from id-s


来源:https://stackoverflow.com/questions/15371102/get-highest-id-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!