为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

GCT1015 2022-10-21 10:30:43
我如何 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);
查看完整描述

3 回答

?
UYOU

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

};


查看完整回答
反对 回复 2022-10-21
?
月关宝盒

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


查看完整回答
反对 回复 2022-10-21
?
呼唤远方

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


查看完整回答
反对 回复 2022-10-21
  • 3 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信