es6基礎系列五--數組的拓展

Array.from()

用於將兩類對象轉爲真正的數組,相似數組對象和可遍歷對象(包括數據結構Set和Map)轉化爲數組
格式:Array.from(arrayLike[, mapFn[, thisArg]])es6

// 字符串
Array.from('foo'); // ["f", "o", "o"]

// Set結構,相似數組,是個集合,具備add,has,delete,clear等方法,後面詳細說
var s = new Set(['foo', window]);
Array.from(s); // ["foo", window]

// Map結構,相似對象,具備size,get,set,has,delete,clear等方法,後面詳細說
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m); // [[1, 2], [2, 4], [4, 8]]


// Array-like object (arguments)
function f() {
  return Array.from(arguments);
}
f(1, 2, 3); // [1, 2, 3]

// 箭頭函數操縱參數,箭頭函數下一節詳細說
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]
// 等同於
Array.from([1, 2, 3]).map(x => x + x)
// 等同於
Array.from([1,2,3]).map(function(x){
    return x+x;
})

Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
// 等同於
Array.from({length: 5}).map((v, i) => i)

Array.of()

用於將一組值,轉換爲數組
格式:Array.of(element0[, element1[, ...[, elementN]]])數組

Array.of(1);         // [1]
Array.of(1, 2, 3);   // [1, 2, 3]
Array.of(undefined); // [undefined]

這個方法的主要目的,是彌補數組構造函數Array()的不足。由於參數個數的不一樣,會致使Array()的行爲有差別。瀏覽器

Array() // []
Array(3) // [undefined, undefined, undefined]
Array(3, 4, 5) // [3, 4, 5]

若是考慮瀏覽器不支持Arrray.of方法,能夠用下面代碼實現數據結構

if (!Array.of) {
  Array.of = function() {
    return Array.prototype.slice.call(arguments);
  };
}

find()和findIndex()

用於找出第一個符合條件的數組元素。
格式:arr.find(callback[, thisArg])
callback是回調函數,找到返回值爲ture則返回該元素,不然返回undefined;
另外,findIndex()和find()相似,只是返回第一個符合條件的數組元素位置,都不符合則返回-1函數

[1, 5, 10, 15].find(function(value, index, arr) {
    return value > 9;
}) // 10
[1, 5, 10, 15].findIndex(function(value, index, arr) {
    return value > 9;
}, window) // 2

[2, 3, NaN, 5].find(function(value, index, arr){
    return Object.is(NaN, value);
}) // NaN
[2, 3, NaN, 5].findIndex(function(value, index, arr){
    return Object.is(NaN, value);
}) // 2

fill()

用於給定值填充數組
格式:arr.fill(value, start, end) start和end表示開始位置、結束位置屬於可選項
可用於數組的初始化,注意:數組中已有的元素,會被替換this

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]

entries(),keys()和values()

格式:arr.entries(), arr.keys(), arr.values()
這三個方法都是用於遍歷數組,其中,entries()是對鍵值對的遍歷,keys()是對鍵名的遍歷、values()是對鍵值的遍歷prototype

for(let i of ["a", "b"].keys()){
    console.log(i);
}
// 0
// 1

for(let el of ["a", "b"].values()){
    console.log(el);
}
// 瀏覽器暫不支持,理論上會輸出a, b的

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

map()

用於提供該數組每一個元素調用一次回調函數返回結果組成的新數組
格式:var new_array = arr.map(callback[, thisArg])code

[1, 4, 9].map(Math.sqrt); // [1, 2, 3]
[1, 4, 9].map(function(num){
    return num*2
}) // [2, 8, 18]
// es6中的 =>
[1, 4, 9].map(num => num*2); // [2, 8, 18]

// 數組裏包含格式化對象
var kvArray = [{key: 1, value: 10},
               {key: 2, value: 20},
               {key: 3, value: 30}];
var newArr = kvArray.map(function(obj){
    var o = {};
    o.key = obj.key;
    o.value = obj.value*2
    return o;
});
console.log(JSON.stringify(newArr)); // [{"key":1,"value":20},{"key":2,"value":40},{"key":3,"value":60}]

filter()

用於提供該數組每一個元素經過回調函數過濾返回結果組成的新數組
格式:var newArray = arr.filter(callback[, thisArg])
注意:跟map()方法的區別,是經過過濾,結果爲ture時的元素,不經過回調函數過濾的則忽略對象

[1, 4, 9].filter(num => num>2); // [4, 9]
[1, 4, 9].map(num => num>2); // [false, true, true]

reduce()

能夠稱之爲迭代器或者累加器,用於把數組中單個元素調用一次回調元素返回結果迭代後再去調用下一個元素,最終返回一個值
格式:arr.reduce(callback, [initialValue]);callback的參數包括accumulator(回調返回的值或初始值)、currentValue(當前元素值)、currentIndex(當前元素索引,可選)、array(數組,可選); initialValue(初始值,可選)索引

[2, 4, 6].reduce(function(acc, cur, index, arr){
    // console.log('累計值爲'+acc+' 當前值爲'+cur+' 當前索引爲'+index);
    // console.log(arr); //能夠查看打印的相關參數
    return acc + cur;
}); // 12 全部元素相加的值

// 有初始值的狀況  =>寫法
[2, 4, 6].reduce((acc, cur) => acc + cur, 10); // 22 初始值10+全部元素相加的值

// 還能夠用於數組合並
[[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
    return a.concat(b);
}); // [0, 1, 2, 3, 4, 5]

// 數組中元素的最大值
[1,2,5,6,3].reduce((acc,cur)=>{
    return Math.max(acc, cur);
}); // 6
相關文章
相關標籤/搜索