一、Array.from()
1、 作用:用於將類數組對象轉化爲數組
let obj = {
'0' : 'a',
'1' : 'b',
'2' : 'c',
length : 3
};
let arr = Array.from(obj);
console.log(arr); //['a', 'b', 'c']
2、 Array.from() 還可以接受第二個參數,用來對每個元素進行處理,將處理後的值放入返回的數組
let obj = {
'0' : '1',
'1' : '2',
'2' : '3',
length : 3
};
let arr = Array.from(obj, y => y * 2);
console.log(arr); //['2', '4', '6']
3、 Array.from() 還可以將字符串轉爲數組,然後返回字符串的長度
function countSymbols(string){
console.log(Array.from(string).length); //6
return Array.from(string);
}
console.log(countSymbols("string")); //['s', 't', 'r', 'i', 'n', 'g']
二、Array.of()
1、 Array.of 方法用於將一組值,轉換爲數組。(總是返回參數值組成的數組,如果沒有參數,就返回一個空數組)
console.log(Array.of(3, 11, 8)) //[3, 11, 8]
console.log(Array.of(3)) //[3]
console.log(Array.of()) //[]
三、 fill()
1、 fill 方法使用給定值,來填充一個數組。fill 方法還可以接受第二個和第三個參數,用於指定填充的起始位置和結束位置
console.log(['a', 'b', 'c', 'd'].fill(3, 1, 3)); //['a', 3, 3, 'd']
四、 includes()
1、 該方法返回一個布爾值,表示某個數組是否包含給定的值(該方法的第二個參數表示搜索的起始位置,默認爲0。如果第二個參數爲負數,則表示倒數的位置,如果這時它大於數組長度(比如第二個參數爲-4,但數組長度爲3)則會重置爲從0開始)
console.log([1, 2, 3].includes(2)); //true
console.log([1, 2, 3].includes(4)); //false
console.log([1, 2, 3].includes(3, 3)); //false
console.log([1, 2, 3].includes(3, -1)); //true
五、 entries() , keys() 和 value()
1、ntries() , keys() 和 value()——用於遍歷數組。他們都返回一個遍歷器對象,可以用 for…of循環,區別事keys() 是對鍵名的遍歷、value() 是對鍵值得遍歷,entries() 是對件值對得遍歷
let arr = ['a', 'b', ''c];
for(let index of arr.keys()) {
console.log(index);
}
// 0
// 1
// 2
for(let elem of arr.values()) {
console.log(elem);
}
// 'a'
// 'b'
// 'c'
for(let [index, elem] of arr.entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
// 2 "c"
六、 find() 和 findIndex()
1、find() 用於找出第一個符合體條件得數組成員。它得參數是一個回調函數,所有數組成員依次執行該回調函數,直到中找出第一個返回值爲 true 的成員,然後返回該成員。如果沒有符合條件的成員,則返回undefined。
let arr = [1, 4, -5, 10, -3];
console.log(arr.find((n) => n < 0)) // -5
2、findIndex() 返回第一個符合體條件的數組成員的位置,如果所有成員都不符合條件,則返回 -1。
let arr = [1, 4, -5, 10, -3];
console.log(arr.findIndex((n) => n < 0)); // 2
3、這兩個方法都可以接受第二個參數,用來綁定回調函數的 this 對象
let arr = [10, 12, 26, 15];
function f(v) {
return v > this.age;
}
let person = {name: 'John', age: 20};
console.log(arr.find(f, person)); // 26
console.log(arr.findIndex(f, person)); // 2