本文主要是介绍ES6-数组的新增特性-扩展运动符,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
构造函数的新增方法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>
这篇关于ES6-数组的新增特性-扩展运动符的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!