Q1: 求數組中最大值
js中不提供求數組最大元素的函數,Math,.max也不接受數組作為參數
apply 接受數組參數佳镜,把數組參數拆開,做了[args] -> arguments的動作
//ES6
Math.max(...[1,22,567,34,22])
//等同于
Math.max(1,22,567,34,22)
//ES5的做法
Math.max.apply(null,[1,22,567,34,22])
Q2:將一個數組push到另一個數組
//ES6
let arr1 = [0,1,2];
let arr2 = [3,4,5];
arr1.push(...arr2);
//ES5
Array.prototype.push.apply(arr1.arr2);
Q3 復制數組
數組是復合的數據類型烤低,直接復制的話吃环,只是復制 了指向底層數據結構的指針计露,而不是克隆一個全新的數組
concat不改變原數組啤挎,返回兩個數組連接之后的新數組,ES5使用猥瑣的方法復制數組
//ES6
const a1 = [1,2];
//方式一
const a2 = [...a1];
//方式二
const [...a2] = a1;
//ES5
const a2 = a1.concat();
Q4: 合并數組
這兩種方法都是淺拷貝炭玫,因為他們的成員是對原數組的引用奈嘿,如果修改了原數組的成員,會同步反映到新數組吞加。
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];
//ES6
[...arr1,...arr2,...arr3];
//ES5
arr1.concat(arr2,arr3);
Q5: 與結構賦值結合裙犹,用于生成數組
數組的slice(from,end)方法,從原數組截取from到end(不包含)的元素衔憨,返回一個新的數組叶圃。
//ES6
[a,...rest] = list;
//ES5
a = list[0],
rest = list.slice(1);
Q6: 字符串轉為數組
[..."hello"]
// [ "h", "e", "l", "l", "o" ]
Q7: 將類數組對象轉化為真正的數組
實現了Iterator接口的對象可以用擴展運算符轉為真正的數組
沒有實現Iterator接口的類數組對象可以用Array.from轉為真正的數組
//實現了Iterator的對象
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
//未實現Iterator的對象
let arrayLike = {
'0' : 'a',
'1' : 'b',
'2' : 'c',
length: 3
};
let arr = [...arrayLike];
// TypeError: Cannot spread non-iterable object.
let arr = Array.from(arrayLike);
//ES5
var arr = [].slice.call(arrayLike);
Q8:Map和Set結構,Generator函數
擴展運算符內部調用的是數據結構的Iterator接口巫财,只要具有Iterator接口的對象盗似,都可以使用擴展運算符。
Generator函數運行后平项,返回一個遍歷器對象,因此也可以是用擴展運算符悍及。
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys];//[1,2,3]
//Generator
const go = function*(){
yield 1;
yield 2;
yield 3;
};
[...go()] //[1,2,3]