这是在每个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 :(得分:2)
您必须更改此项以获取下一项的名称:
console.log('its name is '+a[i+1]);
尝试使用for循环(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 :(得分: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));
}
答案 2 :(得分: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));
});
答案 3 :(得分: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);
}