扩展运算符是三个点(...),主要用于展开数组,将一个数组转为参数序列。下面是扩展运算符的应用情况;
求数组最大元素问题:
(1)用es5中的apply方法将数组转为参数序列,然后用Math.max()求数组中的最大元素:
function f(x,y,z){
console.log(Math.max(x,y,z));
}
var args = [1,3,2];
f.apply(null,args);
//下面语句或许更简洁一点
Math.max.apply(null,[3,4,1]);
(2)用es6中的扩展运算符将数组转为参数序列,然后用Math.max()求数组中的最大元素:
function f(x,y,z){
console.log(Math.max(x,y,z));
}
var args = [1,3,2];
f(...args);
//下面语句或许更简洁一点
Math.max(...[54,2,1]);
将一个数组追加到另一个数组尾部问题:
(3)通过es5的push()将一个数组追加到另一个数组尾部:
var arr1 = ["a","b"];
var arr2 = ["c","d"];
var arr3 = Array.prototype.push.apply(arr1,arr2);
console.log(arr3);
(4)通过es6的扩展运算符将一个数组追加到另一个数组尾部:
var arr1 = ["a","b"];
var arr2 = ["c","d"];
var arr3 = arr1.push(...arr2);
console.log(arr3);
(1)用es5的concat()来实现数组的合并。
var arr1 = ["a","b"];
var arr2 = ["c","d"];
var arr3 = ["e"];
var arr4 = arr1.concat(arr2,arr3);
console.log(arr4);//[ 'a', 'b', 'c', 'd', 'e' ]
(2)用es6的扩展运算符来实现数组的合并。
var arr1 = ["a","b"];
var arr2 = ["c","d"];
var arr3 = ["e"];
var arr4 = [...arr1,...arr2,...arr3];
console.log(arr4);//[ 'a', 'b', 'c', 'd', 'e' ]
const [head,middle,...tail] = [1,2,3,4,5];
//head = 1;middle = 2;tail = [3,4,5];
const [head,...tail] = [];
//head = undefined;tail = [];
const [head,...tail] = [3];
//head = 3;tail = [];
var arr = [..."hello"];
console.log(arr);
// [ 'h', 'e', 'l', 'l', 'o' ]
(1)JavaScript会将32位的Unicode字符识别为2个字符,采用扩展运算符会消除这个问题。
'x\uD83D\uDE80y'.length;//4
[...'x\uD83D\uDE80y'].length;//3
(2)涉及操作32位字符的函数的规范写法:
function getLength(str){
return [...str].length;
}
getLength('x\uD83D\uDE80y');//3