从索引为 1 到 5 Javascript 的数组中返回项目

我如何 console.log 当前数组中索引 1 到 5 的项目?使用循环


let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]


const mappedCars=cars.map((item, i) => {

    console.log("The current index is: " + i);

    console.log("The current element is: " + item);

    console.log("\n");

    return item; //equivalent to list[index]

});


console.log(mappedCars);


GCT1015
浏览 101回答 3
3回答

UYOU

使用 for 循环:let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]for(i = 1; i<cars.length; i++){&nbsp; &nbsp; console.log("The current index is: " + i);&nbsp; &nbsp; console.log("The current element is: " + cars[i]);&nbsp; &nbsp; console.log("\n");};

月关宝盒

for loop您可以定义初始条件以及循环终止条件。for ([initialExpression]; [condition]; [incrementExpression])&nbsp;statementlet cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]const updated = [];for (let i=1; i<=5; i++) {&nbsp; &nbsp; &nbsp; &nbsp; updated.push(cars[i]);}console.log(updated);

呼唤远方

要在索引 1 到 5(包括) 的循环中执行此操作:let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"]const filteredCars = [];for (let i=1; i<=5; i++) {&nbsp; &nbsp; &nbsp; &nbsp; 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript