js中的map
时间: 2023-07-02 07:07:47 浏览: 51
在 JavaScript 中,`map()` 是一个数组方法,它接受一个函数作为参数,并返回一个新数组,该数组包含了原数组中每个元素被该函数处理后的结果。
`map()` 方法的基本语法如下:
```
array.map(function(currentValue, index, arr), thisValue)
```
其中,`array` 是要进行映射操作的原数组,`function(currentValue, index, arr)` 是对每个元素进行操作的函数,`currentValue` 是当前元素的值,`index` 是当前元素的索引,`arr` 是原数组,`thisValue` 是可选的参数,用于指定函数中 `this` 的值。
下面是一个简单的例子,使用 `map()` 方法将数组中的每个元素都乘以 2:
```javascript
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(function(num) {
return num * 2;
});
console.log(doubledNumbers); // 输出 [2, 4, 6, 8, 10]
```
除了上述例子中的基本用法外,`map()` 方法还可以用于将数组中的元素转换为其他类型,例如将字符串类型的数字转换为数值类型:
```javascript
let strings = ["1", "2", "3", "4", "5"];
let numbers = strings.map(Number);
console.log(numbers); // 输出 [1, 2, 3, 4, 5]
```
还可以使用箭头函数来简化代码:
```javascript
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // 输出 [2, 4, 6, 8, 10]
```