js_数组扩展
2021-04-12 12:26
标签:container 转换 ble OLE div array res 接口 函数 使用三个点可以将数组转为以逗号分隔的参数序列。 只有函数调用时,扩展运算符才可以放在圆括号内 js_数组扩展 标签:container 转换 ble OLE div array res 接口 函数 原文地址:https://www.cnblogs.com/Syinho/p/13354333.html
...arr
example1.将数组转化为以逗号分隔的参数序列
const ARR1 = [1, 2, 3, 4, 5];
console.log(...ARR1); //1 2 3 4 5
example2.将多个数组进行合并
const ARR1 = [15, 146, 58];
const ARR2 = [13, 15, 12];
const ARR3 = [47, 48, 587];
const ARR4 = [...ARR1, ...ARR2, ...ARR3];
console.log(ARR4); //[15, 146, 58, 13, 15, 12, 47, 48, 587]
example3.将数组子项作为参数传递给函数
const ARR1 = [1, 2, 3, 4, 5, 6];
function add(x, y) {
console.log(x + y);
}
add(...ARR1); //3
example4.与解构配合赋值,但要注意扩展运算符必须在最后一个,否则报错。
let arr = [variable1, ...ARR1] = [1, 2, 3, 4, 5, 6];
console.log(variable1); //1
console.log(ARR1); //[2,3,4,5,6]
let arr2 = [...ARR2, variable2] = [1, 2, 3, 4, 5];
console.log(ARR2);
console.log(variable2);//Uncaught SyntaxError: Rest element must be last element
example5.展开实现了Iterator接口的对象
扩展set
let set1 = new Set();
set1.add(1);
set1.add(2);
set1.add(2);
set1.add(3);
console.log(set1); //类数组[1,2,3],可以使用Array.from转换成数组
console.log(Array.from(set1)); //[1,2,3]
console.log(...set1); //1 2 3
扩展map
let map1 = new Map();
map1.set(‘k1‘, 1);
map1.set(‘k2‘, 2);
map1.set(‘k3‘, 3);
console.log(map1);
console.log(Array.from(map1)); //[["k1", 1],["k2", 2],["k3", 3]];
console.log(...map1); //["k1", 1] ["k2", 2] ["k3", 3]]
在数组扩展中添加表达式
var x = 1;
var arr1 = [1, 3, 5, 7, 9];
var arr2 = [2, 4, 6, 8, 10];
const ARR = [...(x > 0 ? arr1 : arr2), "奇数"];
console.log(ARR); //[1, 3, 5, 7, 9, "奇数"]
上一篇:Java 特殊字符正则替换
下一篇:JavaScript:数组