ES6-数组的新增特性-扩展运动符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012054869/article/details/82015768

构造函数的新增方法Array.form()和Array.of()

2.Array.form()

可以把类数组对象、实现了迭代器接口的数据类型转换成真正的对象;

例子:

<script>
	//例子一:类数组对象
    let arrayLike = {
    	0:"苹果",
    	1:"香蕉",
    	2:"西瓜",
    	3:"葡萄",
    	length:4
    }
    console.log(arrayLike);

    //把arrayLike转为纯数组
    let arrList = Array.from(arrayLike);
    console.log(arrList);//Array [ "苹果", "香蕉", "西瓜", "葡萄" ]

    //遍历
    arrList.forEach(function(val,key){
    	console.log(key,val);//0 苹果 1 香蕉 2 西瓜 3 葡萄
    })


    //例子二:实现interator接口的数据,strList转为纯数组
    var strList =Array.from("helloworld");
    console.log(strList);//输出数组Array [ "h", "e", "l", "l", "o", "w", "o", "r", "l", "d" ]

    //遍历
     strList.forEach(function(val,key){
    	console.log(key,val);//0 h 1 e 2 l 3 l 4 o......
    })

     //统一,扩展运算符也可以将字符串转为纯数组,例子
     let arr = [...'hello'];
     console.log(arr);//输出Array [ "h", "e", "l", "l", "o" ]

</script>

 

3. Array.of()

将一组值转化为数组;

例子:

<script>
	let arr = Array.of(10,20,30,40);
    console.log(arr);//输出Array [ 10, 20, 30, 40 ]

    // 等同于
    let arr1 =new Array('a','b','c','d');
    console.log(arr1);//输出Array [ "a", "b", "c", "d" ]


    // Array.of和new Array区别
    // new Array根据参数不同解析的结果不同,而Array.of不会,所以用Array.of代替了new Array
    // 当数组中有一个元素时

    let arr2 = Array.of(10);
    console.log(arr2);//直接输出Array [ 10 ]

    // 当用new Array时
    let arr3 = new Array(10);
    console.log(arr3);//直接输出长度为10的数组,Array [ <10 empty slots> ],而不是数组中元素为10
</script>

猜你喜欢

转载自blog.csdn.net/u012054869/article/details/82015768