将属性添加到 for 循环中的最后一项

Add a property to last item in for loop

本文关键字:最后 一项 添加 属性 for 循环      更新时间:2023-09-26
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);

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

if (i == len-1) {
   linkObj.position = "left";
}
// 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";
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);

由于它是您推送到数组中的最后一个项目,因此您也可以在 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";