1.Array.from(obj,MapFn);
其中,obj可以是数组,可以是类数组的对象,可以是set对象
MapFn是数组元素的处理方法
1.1.obj为数组
console.log(Array.from([1, 0, 2, , 3], x => x > 1)); //[false,false,true,false,true]
console.log(Array.from([1, 0, 2, , 3], x => x || 0)); //[1, 0, 2, 0, 3]
1.2.obj为类数组对象
let arrLike = {"0": "3","1": "6","2": "9",length:3};
console.log(Array.from(arrLike, x => x / 3)); //[1,2,3]
1.3.obj为set对象
console.log(Array.from(new Set([1,2,3,4]),x=>x*x)); //[1,4,9,16]
2.Array.from({length:n},Fn);可以将各种值转化成真正的数组
console.log(Array.from({length: 3},()=>'hello world'));
// ["hello world", "hello world", "hello world"]
console.log(Array.from({length: 3},item => item = {"name": "zs","age": 18}));
/* [{…}, {…}, {…}]
0: {name: "zs", age: 18}
1: {name: "zs", age: 18}
2: {name: "zs", age: 18}
length: 3*/
console.log(Array.from({length: 3},(v, i) => item = {index: i}));
/* [{…}, {…}, {…}]
0: {index: 0}
1: {index: 1}
2: {index: 2}
length: 3*/
3. Array.from({string});可以接收一个字符串
console.log(Array.from("hello world"));
//["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
补充:
4.复制数组
let arr = [1,2,3,4,5];
let arr2 = Array.from(arr);
console.log(arr) // [1,2,3,4,5]
console.log(arr2) // [1,2,3,4,5]
5.将伪数组转化为数组
let oli = document.querySelectorAll("li");
console.log(oli); //NodeList(5) [li, li, li, li, li]
let arr2 = Array.from(oli);
console.log(arr2); //(5) [li, li, li, li, li]
本文详细介绍了JavaScript中的Array.from方法,包括其用法和参数解析。通过实例展示了如何利用Array.from转换不同类型的输入,如数组、类数组对象、Set对象,以及创建指定长度的数组。此外,还提到了Array.from在复制数组、处理伪数组和字符串等场景的应用。
324

被折叠的 条评论
为什么被折叠?



