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);

如何将位置:“左”添加到循环中的最后一项?

4

4 回答 4

2
if (i == len-1) {
   linkObj.position = "left";
}
于 2013-11-12T00:09:26.083 回答
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";
于 2013-11-12T00:10:29.270 回答
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);
于 2013-11-12T00:11:08.303 回答
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";
于 2013-11-12T00:17:18.837 回答