Как показать каждое значение и следующее значение?

0

это правильный способ также показать следующее имя элементов в 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 for(var i =0;....) цикла for(var i =0;....) .
Теги:
arrays

4 ответа

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

Ваш код будет работать нормально, хотя вам не нужно условие 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];
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
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);
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню