2013-11-12 5 views
1
for (i = 0; i < len; i++) { 
    dStep = links[i].getAttribute("data-step"), 
    dIntro = links[i].getAttribute("data-intro"), 
    linkObj = { 
     element: "#step" + dStep, 
     intro: dIntro, 
     position: "right" 
    }; 
    obj.steps.push(linkObj); 

Как бы добавить позицию: «осталось» до последнего элемента в цикле?Добавить объект для последнего элемента в цикле

+0

Почему вы не объявляете какие-либо переменные? – elclanrs

ответ

1
// You should almost certainly be using the var keyword 
for (var i = 0; i < len; i++) { 
    var dStep = links[i].getAttribute("data-step"), 
     dIntro = links[i].getAttribute("data-intro"), 
     linkObj = { 
      element: "#step" + dStep, 
      intro: dIntro, 
      position: "right" 
     }; 
    obj.steps.push(linkObj); 
} 
// Take advantage of the fact that JavaScript doesn't have block scoping 
linkObj.position = "left"; 
2
if (i == len-1) { 
    linkObj.position = "left"; 
} 
0
for (i = 0; i < len; i++) { 
    dStep = links[i].getAttribute("data-step"), 
    dIntro = links[i].getAttribute("data-intro"), 
    linkObj = { 
     element: "#step" + dStep, 
     intro: dIntro, 
     position: "right" 
    }; 

    // try this 
    if (i === len - 1) { 
     linkObj.position = 'left'; 
    } 

    obj.steps.push(linkObj); 
0

Поскольку это последний пункт вы толкнули в массив, вы также можете просто добавить/изменить свойство для последнего элемента в массиве после for цикла:

for (i = 0; i < len; i++) { 
    dStep = links[i].getAttribute("data-step"), 
    dIntro = links[i].getAttribute("data-intro"), 
    linkObj = { 
     element: "#step" + dStep, 
     intro: dIntro, 
     position: "right" 
    }; 
    obj.steps.push(linkObj); 
} 

// add this line of code after the for loop 
obj.steps[obj.steps.length - 1].position = "left"; 
Смежные вопросы