3 回答
TA贡献1878条经验 获得超4个赞
使用 for 循环:
let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]
for(i = 1; i<cars.length; i++){
console.log("The current index is: " + i);
console.log("The current element is: " + cars[i]);
console.log("\n");
};
TA贡献1772条经验 获得超5个赞
for loop您可以定义初始条件以及循环终止条件。
for ([initialExpression]; [condition]; [incrementExpression])
statement
let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]
const updated = [];
for (let i=1; i<=5; i++) {
updated.push(cars[i]);
}
console.log(updated);
TA贡献1856条经验 获得超11个赞
要在索引 1 到 5(包括) 的循环中执行此操作:
let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]
const filteredCars = [];
for (let i=1; i<=5; i++) {
filteredCars.push(cars[i]);
}
console.log(filteredCars);
如果没有循环,您也可以使用filter()or slice()。参见示例filter():
let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]
const filteredCars=cars.filter((item, i) => i>=1 && i<=5);
console.log(filteredCars);
添加回答
举报