北京漫步云端网站建设,网站后台管理系统怎么添加框,搜索引擎优化入门,wordpress主菜单下拉箭头怎么设置Array.from()是一个用于从类数组对象或可迭代对象创建新数组的静态方法。 基本语法#xff1a;
Array.from(arrayLike[, mapFunction[, thisArg]])arrayLike: 类数组对象或可迭代对象#xff0c;用于创建新数组。 mapFunction (可选): 对数组中的每个元素进行映射的函数。 t…Array.from()是一个用于从类数组对象或可迭代对象创建新数组的静态方法。 基本语法
Array.from(arrayLike[, mapFunction[, thisArg]])arrayLike: 类数组对象或可迭代对象用于创建新数组。 mapFunction (可选): 对数组中的每个元素进行映射的函数。 thisArg (可选): 执行 mapFunction 时用作 this 的值。
1. 字符串转数组
const str hello;
const newArray Array.from(str);
console.log(newArray); // [h, e, l, l, o]
// 相当于 str.split()2. 用Set 或 Map创建数组
const set new Set([1, 2, 3]);
const newArray Array.from(set);
console.log(newArray); // [1, 2, 3]3. 对元素进行迭代处理
const numbers [1, 2, 3];
const squaredNumbers Array.from(numbers, x x * x);
console.log(squaredNumbers); // [1, 4, 9]
const str helloconst strArr Array.from(str,(s) s_)
console.log(strArr);//[h_, e_, l_, l_, o_]
console.log(strArr.join());// h_e_l_l_o_4. 类数组对象转成真正的数组
什么是类数组对象
const arrayLike { 0: a, 1: b, 2: c, length: 3 };
const newArray Array.from(arrayLike);
console.log(newArray); // [a, b, c]function exampleFn() {console.log(arguments); // { 0: 1, 1: 2, 2: a length:3,...} 类数组对象console.log(Array.from(arguments))//[1, 2, a] 真正的数组console.log([...arguments])//[1, 2, a]}exampleFn(1, 2, a)5. 数组、字符串的去重 const arr [1, 2, 2, 3, 4, 4, 5];const uniqueArray Array.from(new Set(arr));const uniqueArray2 [...new Set(arr)]const uniqueArray3 _.uniq(arr)// 使用lodash中的方法console.log(uniqueArray); // [1, 2, 3, 4, 5]console.log(uniqueArray2); // [1, 2, 3, 4, 5]console.log(uniqueArray3); // [1, 2, 3, 4, 5]6. 创建指定长度的数组 // 数组里创建3个空数组const newArr Array.from({length:3},() [])console.log(newArr)//[[],[],[]]const newArr2 Array.from({ length5}, (_, index) index 1);console.log(newArr2); // [1, 2, 3, 4, 5]// 数组里创建3个空对象const newArr Array.from({length:3},() ({})console.log(newArr)//[{},{},{}]注意
const arr Array.from({length: 5}, () {})
console.log(arr);//[undefined, undefined, undefined, undefined, undefined]映射函数 () {} 不会改变数组的元素的实际值因为它返回的是一个空函数。因此使用 Array.from 时每个元素都会被映射为 undefined。 而映射函数 () ({}) 返回一个新的空对象。每次映射函数调用时都会返回一个新的对象因此每个数组元素都将包含一个新的空对象。