js里遍历数组map用法
时间: 2023-10-30 12:12:01 浏览: 36
JS 中遍历数组可以使用 map() 方法,该方法会对数组中的每个元素进行指定的操作并返回一个新的数组,格式为:
```
newArray = array.map(function(currentValue, index, arr), thisValue)
```
其中,第一个参数为回调函数,可以接受三个参数:
- currentValue:必须。当前元素的值
- index:可选。当前元素的索引
- arr:可选。当前元素属于的数组对象
第二个参数为可选,指定回调函数内 this 的指向。
相关问题
js遍历数组map和foreach
JavaScript中遍历数组有两种常用的方法:map和forEach。它们的区别在于map会返回一个新的数组,而forEach只是遍历数组并执行回调函数。
以下是两种方法的使用示例:
1. 使用map方法遍历数组并返回一个新的数组
```javascript
const arr = [1, 2, 3, 4, 5];
const newArr = arr.map(function(item) {
return item * 2;
});
console.log(newArr); // 输出 [2, 4, 6, 8, 10]
```
2. 使用forEach方法遍历数组并执行回调函数
```javascript
const arr = [1, 2, 3, 4, 5];
arr.forEach(function(item, index, arr) {
arr[index] = item * 2;
});
console.log(arr); // 输出 [2, 4, 6, 8, 10]
```
需要注意的是,使用forEach方法改变原数组的元素时,需要通过索引来修改,而不能直接修改item的值。
js遍历数组的map方法
以下是使用JavaScript中map方法遍历数组的例子:
1. 使用map方法遍历数组并返回新数组
```javascript
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1); // 输出:[2, 8, 18, 32]
```
2. 使用map方法遍历对象数组并返回新数组
```javascript
const items = [
{ name: 'apple', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'banana', type: 'fruit' },
];
const itemNames = items.map(item => item.name);
console.log(itemNames); // 输出:['apple', 'carrot', 'banana']
```