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 :(得分:2)
if (i == len-1) {
linkObj.position = "left";
}
答案 1 :(得分: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 :(得分: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);
答案 3 :(得分: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";