当前位置:网站首页>js Array.from()的5个便捷应用
js Array.from()的5个便捷应用
2022-06-30 01:24:00 【棠樾】
任何编程语言都具有超出基本用法的功能。这个要归功于成功的设计和它试图解决的广泛问题。
Array.from():一个允许对js集合(数组,类数组对象,字符串,映射,集合等可迭代对象)进行大量有用转换的主力。
基本语法:
Array.from(arrayLikeOrIterable[, mapFunction[, thisArg]])- arrayLikeOrIterable:必传参数,类数组对象或者一个iterable
- mapFunction:可选参数,mapFunction(item,index){ ... }对集合中的每一个项目调用的函数,返回的值被插入到新的集合中。
- thisArg:可选参数,执行回调函数mapFunction时this对象,这个参数很少使用。
例如:我们将类数组对象数量乘以2:
const someNumbers = { '0':10, '1': 15, length: 2};
Array.from(someNumbers, value => value * 2); // [20, 30]将类数组对象转换成真正的数组
通常我们会在函数内部或者使用DOM集合时遇到一些类数组对象,例如:arguments
我们可以对函数的参数求和:
function sumArguments() {
return Array.from(arguments).reduce((sum, value) => sum + value);
}
sumArguments(1,2,3); // 6在上例中,Array.from(arguments)将类数组arguments转换成真正的数组。然后对新数组求和。
此外,Array.from()还可以与任何实现可迭代协议的对象或者原语一起使用,让我们看下面几个例子:
Array.from('Hey'); // ['H','e','y']
Array.from(new Set(['one', 'two']); // ['one', 'two']
const map = new Map();
map.set('one', 1);
map.set('two', 2);
Array.from(map); // [['one', 1], ['two', 2]]2.克隆一个数组
Array.from()可以浅拷贝一个数组
const a= [3, 6, [4,7,8], 9];
const b= Array.from(a);
a[2].push(5);
console.log(a) // [3, 6, [4,7,8,5], 9];
console.log(b) // [3, 6, [4,7,8,5], 9];
console.log(a===b) // false这里讲一下深拷贝和浅拷贝的区别:
浅拷贝:只复制指向某个对象的指针,而不复制对象本身,新旧对象还是共享同一块内存。浅拷贝是该对象重新开辟内存空间,但是对象内部的嵌套对象用原来嵌套对象的引用,=号才是直接对原对象取引用的操作。
深拷贝:会另外创造一个一模一样的对象(在内存中新开辟一块内存地址)对象内的嵌套的对象也要重新开辟内存空间,新对象和原对象不共享同一块内存,修改新对象不会影响到原对象。、
总结:浅拷贝是拷贝一层,深拷贝是递归拷贝
Array.from是浅拷贝,它只拷贝了第一层的数据,第二层及以后的对象级别的只拷贝了指针。 浅拷贝过来的数据只有第一层数据不是共享的,第二层乃至第三层的数据和源对象是共享的。而深拷贝是和源对象没有任何共享的
3.使用值填充数组
如果你需要使用相同的值来初始化数组,那么Array.from()将是不错的选择。
我们来定义一个函数,创建一个填充相同默认值得数组:
const length =4;
const init = 1;
const result = Array.from( { length }, () => init ); // result [1,1,1,1]
我们可以使用 array.fill() 实现同样的功能
const length = 3;
const init = 0;
const result = Array(length).fill(init) // result [0,0,0]3.1使用对象填充数组
当初始化数组的每一项都应该是一个新对象时,Array.from()是一个更好的解决方案:
const length = 3;
const resultA = Array.from({ length }, () => ({}));
const resultB = Array(length).fill({});
resultA; // => [{}, {}, {}]
resultB; // => [{}, {}, {}]
resultA[0] === resultA[1]; // => false
resultB[0] === resultB[1]; // => true
由Array.from() 返回的 resultA 使用不同空对象实例进行初始化。之所以发生这种情况是因为每次调用时,mapFunction,即此处的 () => ({}) 都会返回一个新的对象。
然后,fill() 方法创建的 resultB 使用相同的空对象实例进行初始化。不会跳过空项。
4.生成数字范围
可以使用Array.from()生成值范围,例如:生成一个0到end-1之间的数字组成的数组
function range(end) {
return Array.from( {length: end}, (_,index) => index)
}
range(4); // [0,1,2,3]5.数组去重
由于Array.from()的入参是可迭代对象,因而我们可以利用其与Set结合来实现快速从数组中删除重复项。
function unique(array) {
return Array.from(new Set(array))
}
unique([1,1,2,2,3,3]) // [1,2,3]首先,new Set(array)创建了一个包含数组的集合,Set集合会删除重复项。因此Set集合是可迭代的,所以可以使用Array.from()将其转换为一个新的数组。这样就实现了数组的去重。
边栏推荐
- ES6 synchronous asynchronous execution and block level scope
- Solution to webkitformboundaryk in post request
- Sentinel source code analysis Chapter 9 - core process - lookprocesschain finding resource processing chain
- Seata 与三大平台携手编程之夏,百万奖金等你来拿
- Cookie加密12
- Varnish 基础概览7
- Newton method (optimization of two variable functions)
- JS recursive summation 1-100
- What is digital garbage? Follow the world's first AI artist to explore meta carbon Art
- 城市规划馆在设计制作上需要注意什么
猜你喜欢

Interface Association of postman

ctfshow 大赛原题 680-695

Text classification using huggingface

Embedded exit (review and release)

Pytroch Learning Notes 6: NN network layer convolution layer

Stimulus reports reporting tool, stimulus creates and builds reports

Precautions for postoperative fundus hemorrhage / / must see every day

Ansible ad-hoc 临时命令

【Games101】Transformation
![[recommendation system] concise principle and code implementation of user based collaborative filtering](/img/3b/d46e37e7ae245cf2931d32d1ebbe4c.png)
[recommendation system] concise principle and code implementation of user based collaborative filtering
随机推荐
The 8th "Internet +" competition - cloud native track invites you to challenge
[Thesis Writing] English thesis writing guide
Some thoughts on small program subcontracting and verification of uiniapp subcontracting optimization logic
Database application
[MRCTF2020]Ezpop-1|php序列化
Sentinel source code analysis Part 8 - core process - sphu Entry current limiting execution
Ansible ad-hoc temporary command
Varnish 基础概览4
田口实验法
Understanding of int argc, char * * argv in C language main function
Cub school learning: manual query and ADC in-depth use
Interview summary
postman 之接口关联
Sklearn notes: make_ Blobs generate clustering data
Cookie加密15 登录加密
阅读,是最廉价的高贵
Quick pow: how to quickly find power
Error reporting in Luban H5 installation
js逆向请求参数加密:
Varnish 基础概览6