记录一下我对map()和Array.from()的实验【2021.11.23】

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // Aarry.from( )还接收第二个可选的映射函数参数。这个参数可以直接增强新数组的值,而无需像调用Array.from( ).map( )那样先创建一个中间数组。
    // 还可以接收第三个可选参数,用于指定映射函数中的this的值。但这个重写的this值在箭头函数中不适用。
    const a1 = [1, 2, 3, 4];
    const a2 = Array.from(a1, x => x ** 2);
    const a3 =
        Array.from(a1, function (x) { return x ** this.exponent }, { exponent: 3 });//第三个就是一个对象,它为第二个函数的this指向
    console.log(a2);  // [1, 4, 9, 16]
    console.log(a3);  // [1, 8,27, 64]



    let array = [1, 2, 3, 5];
    //    array[6]=11;
    //    console.log(array);
    //    console.log(array[4]);//undefinde

    //console.log(array.forEach(()=>"中国"));//undefinde
    // array.forEach(function (x,index,arr) {//引用地址指向同一个地址
    //     arr[index] = "中国";
    // })
    // console.log(array)//[ "中国", "中国", "中国", "中国" ]

    // let ay = array.map(()=>'中国')
    // console.log(ay);//[ "中国", "中国", "中国", "中国" ]

    let ay = array.map(function(){
         return '中国';
    })
    console.log(ay);//[ "中国", "中国", "中国", "中国" ]

    // let new_array = Array.from(array,function(){
    //   return '中国'//箭头函数单条处理可以省略return和{大括号}
    // });
    // console.log(new_array)//[ "中国", "中国", "中国", "中国" ]
    
    let array = [1, 2, 3, 5];
    let new_array = Array.from(array,()=>'中国');
    console.log(new_array)//[ "中国", "中国", "中国", "中国" ]

    // array.forEach(function(valve){
    //     valve=valve+1;
    //     console.log(valve);//有
    // })
    // console.log(array)//未改变
</script>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值