JavaScript Array map() 方法

Array map() 方法

通过指定函数处理数组的每个元素,并返回处理后的数组。map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

map() 方法按照原始数组元素顺序依次处理元素, map() 不会对空数组进行检测,map() 不会改变原始数组。

语法:array.map(function(currentValue,index,arr), thisValue)

参数 描述
function(currentValue, index,arr) 必须。函数,数组中的每个元素都会执行这个函数
函数参数:
参数 描述
currentValue 必须。当前元素的值
index 可选。当前元素的索引值,从0开始
arr 可选。当前元素属于的数组对象
thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

JavaScript 版本:    1.6

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>箭头函数</title>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

    <!-- ES6 时,script 的 type 需要标识成 module,否则箭头函数编译不通过,即无法识别-->
    <script type="module">
        $(function () {
            let arr1 = [1, 2, 3, 4, 5];
            /**
             * 通过指定函数处理数组的每个元素,并返回处理后的数组。
             * 如下所示对数组中的每个元素进行平方操作
             * @type {Array}
             */
            let arr2 = arr1.map(function (currentValue, index) {
                console.log("当前处理数组元素,index=" + index + ",value=" + currentValue);
                return currentValue * currentValue;
            });
            console.log(arr1.toString());//原数组的值不变
            console.log(arr2.toString());//新数组的值为原数组的值的平方
        });
    </script>
</head>
<body>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/wangmx1993328/article/details/84066490