使用javascript获取最高id

使用javascript获取最高id,javascript,jquery,Javascript,Jquery,我有一堆笔记divs,格式如下: <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"> 快速和肮脏的方式: var max = 0; $('.note-row').each(function(

我有一堆笔记
div
s,格式如下:

<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">
快速和肮脏的方式:

var max = 0;
$('.note-row').each(function() {
    max = Math.max(this.id, max);
});
console.log(max); 
这是一个略短且更复杂的方法(用于使用,也允许将负ID降到
Number.negative_INFINITY
,正如Blazemonger所建议的):


你可以这样做:

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

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

与查找任何max、loop的方法相同:

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

$('.note-row').each(function() {
    var idAsNumber = parseInt(this.id, 10);
    if (idAsNumber  > max) {
        max = idAsNumber;
    }
});
var maxID=-1;
$('.note row')。每个(函数(){
var myid=parseInt($(this).attr('id'),10);
如果(maxID
很有趣,但这也很有效:

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

为了完整性,优化的解决方案:

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);
var n=document.getElementsByClassName('note-row'),
m=数字负_无穷大,
i=0,
j=n.长度;

对于(;i根据HTML规范,ID不能以数字开头。HTML5和更高版本除外。如果元素按ID顺序排列,并且只有这些元素具有class
note row
,则可以使用
.last
->
$('.note row').last()[0].id
+1,比使用
map
sort
max=Math.max(此.id,max)的另一个答案更有效
随时都比if-then语句好。@Blazemonger谢谢。我想知道我是否也需要添加parseInt,Math.max也应该处理这个问题。更新了。我要推一个初始值
max=Number。这里也是负的
:-)用
get
替换
toArray
,因为它比较短。;-)但这对我来说并不是最高的。我拥有的集合中最高的是20,而这给了我9。除了效率低下之外,这不会像
那样起作用。JS中的sort
不会像你所期望的那样处理数字。@Dogbert:如果你想提高效率,首先不要使用jQuery。
max=Number。负无穷大
是您要查找的初始值。理想情况下,排序比较器函数应该返回-1,而不是0或1。@Vega我知道,但在这种情况下,没有必要,因为我们要查找最大值。无论如何,我提供这个解决方案只是出于好奇。当然它很烂,如果不一定是最短的代码。
  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
var max = $('.note-row').sort(function(a, b) { return +a.id < +b.id })[0].id;
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);