2013-12-18 22 views
0

這是正確的方式來顯示下一個項目名稱在jquery每個還是有更好的方法嗎?jquery如何顯示每個值和下一個值?

a=[4,5,89,2,19]; 

$(a).each(function(i,v){ 

    console.log('this item is called '+v+' at position '+i); 

    if(i<a.length){ 
     console.log('the next item is at position '+(i+1)); 
     console.log('its name is '+a.indexOf(i+1)); 
     } 
}); 
+0

你爲什麼不使用本地JavaScript'爲(VAR I = 0; ....)'循環。 –

回答

2

您必須更改此名稱以獲取下一個項目的名稱:

console.log('its name is '+a[i+1]); 

與循環(JS)試試:

 a=[4,5,89,2,19]; 

     for(var i=0;i<a.length-1;i++){ 
      console.log("this item is called:"+a[i]+" at position:"+i); 

      if(a[i+1]!=undefined){ 
       console.log("next item is called:"+a[i+1]+" at position:"+(i+1)); 
     } 
} 
1

嘗試:

a=[4,5,89,2,19]; 
var len = a.length; 
for(var i=0;i<len-1;i++){ //loop length-1, to get next element 
    console.log("current value:"+a[i]+" at position:"+i); 
    console.log("next value:"+a[i+1]+" at position:"+(i+1)); 
} 
1

您的代碼將正常工作,雖然你並不需要在那裏if條件爲each永遠不會重複過去的數組的邊界:

a = [4, 5, 89, 2, 19]; 

$(a).each(function(i, v){ 
    console.log('this item is called ' + v + ' at position ' + i); 
    console.log('the next item is at position ' + (i + 1)); 
    console.log('its name is ' + a.indexOf(i + 1)); 
}); 
1
a=[4,5,89,2,19]; 
console.log("length of array a: " + a.length.toString()); 
for(var i=0; i < a.length; i++){ 
    var str = ""; 
    if(i == (a.length - 1)) 
    { 
     str += "current index: " + i.toString() + "; current value: " + a[i].toString() + ; 
    } 
    else 
    { 
     str += "current index: " + i.toString() + "; current value: " + a[i].toString() + "; next value: "+ a[i+1].toString(); 
    } 
    console.log(str); 
} 
相關問題