JavaScript 数组遍历:获取指定位置的值
可以使用数组的 forEach() 方法遍历数组,并使用 if 语句判断当前位置是否为 5、8、15,然后将对应的值保存到一个新数组中。
示例代码如下:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let result = [];
arr.forEach((item, index) => {
if (index === 4 || index === 7 || index === 14) {
result.push(item);
}
});
console.log(result); // [5, 8, 15]
解析:
- 首先定义一个有 20 个元素的数组 arr。
- 然后定义一个空数组 result,用于保存取到的值。
- 使用数组的 forEach() 方法遍历 arr,传入一个回调函数,该函数接收两个参数:当前元素 item 和当前索引 index。
- 在回调函数中,使用 if 语句判断当前索引是否为 5、8、15,如果是,则将对应的元素 item 添加到 result 数组中。
- 最后输出 result 数组,即取到的三个值的数组。
原文地址: https://www.cveoy.top/t/topic/mAOO 著作权归作者所有。请勿转载和采集!