您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 佛山分类信息网,免费分类信息发布

es6数组怎么求并集

2024/2/20 14:47:01发布23次查看
3种方法:1、用set对象和扩展运算符,语法“array.from(new set([...a,...b]))”;2、用set对象和遍历语句,语法“a.foreach(i=>{b.push(i);})let u=array.from(new set(b));”;3、用set对象和concat(),语法“array.from(new set(a.concat(b)))”。
本教程操作环境:windows7系统、ecmascript 6版、dell g3电脑。
es6数组求并集的3种方法
方法1:利用set对象和扩展运算符“...”
利用扩展运算符“...”合并两个数组
利用set对象去重
set是es6新提供的数据结构,类似于数组,但是本身没有重复值。利用这一特性,我们可以将数组转为set类型进行去重,然后使用array.from方法将其再转为数组。
示例:
let a=[1, 2, 3];let b=[3, 5, 2];console.log(a);console.log(b);// 并集let unionset = array.from(new set([...a, ...b]));console.log("并集:");console.log(unionset);
方法2:利用set对象和遍历语句
利用foreach()和push()合并两个数组
用foreach()遍历a数组,用push()将a数组的元素一个个添加到b数组的末尾
利用set对象去重
示例:
let a=[1, 2, 3];let b=[3, 5, 2];console.log(a);console.log(b);a.foreach(item => { b.push(item);})// 并集let unionset = array.from(new set(b));console.log("并集:");console.log(unionset);
方法3:利用set对象和concat()
concat() 方法用于连接两个或多个数组。
array1.concat(array2,array3,...,arrayx)
会返回一个新的数组。该数组是通过把所有 arrayx 参数添加到 arrayobject 中生成的。如果要进行 concat() 操作的参数是数组,那么添加的是数组中的元素,而不是数组。
示例:
let a=[1, 2, 3];let b=[2, 4, 6];console.log(a);console.log(b);// 并集let unionset = array.from(new set(a.concat(b)));console.log("并集:");console.log(unionset);
【相关推荐:javascript视频教程、web前端】
以上就是es6数组怎么求并集的详细内容。
佛山分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录