ES6的数组扩展( Array.from()方法 )

Array.from()方法用于将类数组和可遍历的集合对象转为真正的数组,这样他们就能够使用数组中的方法来处理数据了。

一、把获取到元素的类数组集合转化为真正的数组
let aP = document.querySelectorAll("p");
var arrP = Array.from(aP);
arrP.forEach(function(item){ //转化为真正的数组之后就能使用数组的forEach方法了
	console.log(item);
});
二、把字符串转化为字符串数组
let str = "hello";
let arrStr = Array.from(str);
//等价于 let arrStr = str.split("");
console.log(arrStr); // ["h", "e", "l", "l", "o"]
三、传入两个参数时,有映射功能
let arr = Array.from([1,3,5],function(item){
    return item * 2 ;
});
console.log(arr); // [2,6,10]

猜你喜欢

转载自blog.csdn.net/m0_38134431/article/details/83856816