问题
I have a bunch of note div
s 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