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

position: "left" をループの最後の項目にのみ追加するにはどうすればよいでしょうか?

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これは配列にプッシュした最後の項目であるため、ループ後に配列の最後の項目のプロパティを追加/変更することもできます。

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 に答える
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 に答える