js Array map

2019年01月03日 20:37 | 1969次浏览 作者原创 版权保护

javascript Array map()函数使用方法


定义

对数组中的每个元素进行处理,得到新的数组,不会改变原始数组。


语法

array.map(function(currentValue,index,arr), thisValue);


参数说明

参数描述
function(currentValue, index,arr)

必须。函数,数组中的每个元素都会执行这个函数

函数参数:

currentValue 必须。当前元素的值

index 可选。当前元素的索引值

arr 可选。当前元素属于的数组对象


thisValue

可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。

如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。


实例

<script type="text/javascript">
const array = [1, 3, 6, 9];
const newArray = array.map(function (value) {
  return value + 1;
});
alert(newArray);
alert(array);

</script>

运行结果

2,4,7,10

1,3,6,9


类似方法: for in , for , foreach

实例

const newArray2 = [];
for (var i in array) {
  newArray2.push(array[i] + 1);
}
 
const newArray3 = [];
for (var i = 0; i < array.length; i++) {
  newArray3.push(array[i] + 1);
}
 
const newArray4 = [];
array.forEach(function (key) {
  newArray4.push(key * key);
})
 
console.log(newArray2);
console.log(newArray3);
console.log(newArray4);
console.log(array);

结果:

[2, 4, 7, 10]

[2, 4, 7, 10]

[2, 4, 7, 10]

[1, 3, 6, 9]

对比:

1、.map()方法使用return,进行回调;其他方法可不需要。

2、.map()方法直接对数组的每个元素进行操作,返回相同数组长度的数组;其他方法可扩展数组的长度



小说《我是全球混乱的源头》
此文章本站原创,地址 https://www.vxzsk.com/1979.html   转载请注明出处!谢谢!

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程