成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

「干貨」細(xì)說 Array 的常用操作(ES5 和 ES6)

VincentFF / 639人閱讀

摘要:今天,會(huì)更具體地將數(shù)組的常用操作進(jìn)行歸納和匯總,以便備不時(shí)之需。在公用庫(kù)中,一般會(huì)這么做的判斷新增的操作和傳入一個(gè)回調(diào)函數(shù),找到數(shù)組中符合當(dāng)前搜索規(guī)則的第一個(gè)元素,返回這個(gè)元素,并且終止搜索。

前言

上一篇文章「前端面試題系列8」數(shù)組去重(10 種濃縮版) 中提到了不少數(shù)組的常用操作。

今天,會(huì)更具體地將數(shù)組的常用操作進(jìn)行歸納和匯總,以便備不時(shí)之需。每組方法都會(huì)配以示例說明,有時(shí)我也會(huì)忘了某個(gè)方法是否會(huì)返回一個(gè)新的數(shù)組,如果你也有類似的困惑,那么看這篇就夠了。希望能幫到有需要的同學(xué)。

ES5 中 Array 操作 1、forEach

Array 方法中最基本的一個(gè),就是遍歷,循環(huán)?;居梅ǎ?b>[].forEach(function(item, index, array) {});

const array = [1, 2, 3];
const result = [];

array.forEach(function(item) {
    result.push(item);
});
console.log(result); // [1, 2, 3]
2、map

map 方法的作用不難理解,“映射”嘛,也就是原數(shù)組被 “映射” 成對(duì)應(yīng)的新數(shù)組?;居梅ǜ?forEach 方法類似:[].map(function(item, index, array) {}); 下面這個(gè)例子是數(shù)值項(xiàng)求平方:

const data = [1, 2, 3, 4];
const arrayOfSquares = data.map(function (item) {
    return item * item;
});
alert(arrayOfSquares); // 1, 4, 9, 16
3、filter

filter 為 “過濾”、“篩選” 之意。指數(shù)組 filter 后,返回過濾后的新數(shù)組。用法跟 map 極為相似:[].filter(function(item, index, array) {});

filter 的 callback 函數(shù),需要返回布爾值 true 或 false。返回值只要 弱等于 Boolean 就行,看下面這個(gè)例子:

const data = [0, 1, 2, 3];
const arrayFilter = data.filter(function(item) {
    return item;
});
console.log(arrayFilter); // [1, 2, 3]
4、some 和 every

some 意指“某些”,指是否 “某些項(xiàng)” 合乎條件。也就是 只要有1值個(gè)讓 callback 返回 true 就行了?;居梅ǎ?b>[].som(function(item, index, array) {});

const scores = [5, 8, 3, 10];
const current = 7;

function higherThanCurrent(score) {
    return score > current;
}

if (scores.some(higherThanCurrent)) {
    alert("one more");
}

every 跟 some 是一對(duì)好基友,同樣是返回 Boolean 值。但必須滿足每 1 個(gè)值都要讓 callback 返回 true 才行。改動(dòng)一下上面 some 的例子:

if (scores.every(higherThanCurrent)) {
    console.log("every is ok!");
} else {
    console.log("oh no!");        
}
5、concat

concat() 方法用于連接兩個(gè)或多個(gè)數(shù)組。該方法不會(huì)改變現(xiàn)有的數(shù)組,僅會(huì)返回被連接數(shù)組的一個(gè)副本。

const arr1 = [1,2,3];
const arr2 = [4,5];
const arr3 = arr1.concat(arr2);
console.log(arr1); // [1, 2, 3]
console.log(arr3); // [1, 2, 3, 4, 5]
6、indexOf 和 lastIndexOf

indexOf 方法在字符串中自古就有,string.indexOf(searchString, position)。數(shù)組這里的 indexOf 方法與之類似。
返回整數(shù)索引值,如果沒有匹配(嚴(yán)格匹配),返回-1.

fromIndex可選,表示從這個(gè)位置開始搜索,若缺省或格式不合要求,使用默認(rèn)值0。

const data = [2, 5, 7, 3, 5];
console.log(data.indexOf(5, "x"));  // 1 ("x"被忽略)
console.log(data.indexOf(5, "3")); // 4 (從3號(hào)位開始搜索)

console.log(data.indexOf(4));    // -1 (未找到)
console.log(data.indexOf("5")); // -1 (未找到,因?yàn)? !== "5")

lastIndexOf 則是從后往前找。

const numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2);     // 3
numbers.lastIndexOf(7);     // -1
numbers.lastIndexOf(2, 3);  // 3
numbers.lastIndexOf(2, 2);  // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3
7、reduce 和 reduceRight

reduce 是JavaScript 1.8 中才引入的,中文意思為“歸約”?;居梅ǎ?b>reduce(callback[, initialValue])

callback 函數(shù)接受4個(gè)參數(shù):之前值(previousValue)、當(dāng)前值(currentValue)、索引值(currentIndex)以及數(shù)組本身(array)。

可選的初始值(initialValue),作為第一次調(diào)用回調(diào)函數(shù)時(shí)傳給previousValue的值。也就是,為累加等操作傳入起始值(額外的加值)。

var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
    return previous + current;
});
console.log(sum); // 10

解析:

因?yàn)閕nitialValue不存在,因此一開始的previous值等于數(shù)組的第一個(gè)元素

從而 current 值在第一次調(diào)用的時(shí)候就是2

最后兩個(gè)參數(shù)為索引值 index 以及數(shù)組本身 array

以下為循環(huán)執(zhí)行過程:

// 初始設(shè)置
previous = initialValue = 1, current = 2

// 第一次迭代
previous = (1 + 2) =  3, current = 3

// 第二次迭代
previous = (3 + 3) =  6, current = 4

// 第三次迭代
previous = (6 + 4) =  10, current = undefined (退出)

有了reduce,我們可以輕松實(shí)現(xiàn)二維數(shù)組的扁平化:

var matrix = [
  [1, 2],
  [3, 4],
  [5, 6]
];

// 二維數(shù)組扁平化
var flatten = matrix.reduce(function (previous, current) {
    return previous.concat(current);
});
console.log(flatten); // [1, 2, 3, 4, 5, 6]

reduceRight 跟 reduce 相比,用法類似。實(shí)現(xiàn)上差異在于reduceRight是從數(shù)組的末尾開始實(shí)現(xiàn)。

const data = [1, 2, 3, 4];
const specialDiff = data.reduceRight(function (previous, current, index) {
    if (index == 0) {
        return previous + current;
    }
    return previous - current;
});
console.log(specialDiff);  // 0
8、push 和 pop

push() 方法可向數(shù)組的末尾添加一個(gè)或多個(gè)元素,返回的是新的數(shù)組長(zhǎng)度,會(huì)改變?cè)瓟?shù)組。

const a = [2,3,4];
const b = a.push(5);
console.log(a);  // [2,3,4,5]
console.log(b);  // 4
// push方法可以一次添加多個(gè)元素push(data1, data2....)

pop() 方法用于刪除并返回?cái)?shù)組的最后一個(gè)元素。返回的是最后一個(gè)元素,會(huì)改變?cè)瓟?shù)組。

const arr = [2,3,4];
console.log(arr.pop()); // 4
console.log(arr);  // [2,3]
9、shift 和 unshift

shift() 方法用于把數(shù)組的第一個(gè)元素從其中刪除,并返回第一個(gè)元素的值。返回第一個(gè)元素,改變?cè)瓟?shù)組。

const arr = [2,3,4];
console.log(arr.shift()); // 2
console.log(arr);  // [3,4]

unshift() 方法可向數(shù)組的開頭添加一個(gè)或更多元素,并返回新的長(zhǎng)度。返回新長(zhǎng)度,改變?cè)瓟?shù)組。

const arr = [2,3,4,5];
console.log(arr.unshift(3,6)); // 6
console.log(arr); // [3, 6, 2, 3, 4, 5]
// tip:該方法可以不傳參數(shù),不傳參數(shù)就是不增加元素。
10、slice 和 splice

slice() 返回一個(gè)新的數(shù)組,包含從 start 到 end (不包括該元素)的 arrayObject 中的元素。返回選定的元素,該方法不會(huì)修改原數(shù)組。

const arr = [2,3,4,5];
console.log(arr.slice(1,3));  // [3,4]
console.log(arr);  // [2,3,4,5]

splice() 可刪除從 index 處開始的零個(gè)或多個(gè)元素,并且用參數(shù)列表中聲明的一個(gè)或多個(gè)值來替換那些被刪除的元素。如果從 arrayObject 中刪除了元素,則返回的是含有被刪除的元素的數(shù)組。splice() 方法會(huì)直接對(duì)數(shù)組進(jìn)行修改。

const a = [5,6,7,8];
console.log(a.splice(1,0,9)); //[]
console.log(a);  // [5, 9, 6, 7, 8]

const b = [5,6,7,8];
console.log(b.splice(1,2,3));  //v[6, 7]
console.log(b); // [5, 3, 8]
11、sort 和 reverse

sort() 按照 Unicode code 位置排序,默認(rèn)升序。

const fruit = ["cherries", "apples", "bananas"];
fruit.sort(); // ["apples", "bananas", "cherries"]

const scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]

reverse() 方法用于顛倒數(shù)組中元素的順序。返回的是顛倒后的數(shù)組,會(huì)改變?cè)瓟?shù)組。

const arr = [2,3,4];
console.log(arr.reverse()); // [4, 3, 2]
console.log(arr);  // [4, 3, 2]
12、join

join() 方法用于把數(shù)組中的所有元素放入一個(gè)字符串。元素是通過指定的分隔符進(jìn)行分隔的,默認(rèn)使用","號(hào)分割,不改變?cè)瓟?shù)組。

const arr = [2,3,4];
console.log(arr.join());  // 2,3,4
console.log(arr);  // [2, 3, 4]
13、isArray

Array.isArray() 用于確定傳遞的值是否是一個(gè) Array。一個(gè)比較冷門的知識(shí)點(diǎn):其實(shí) Array.prototype 也是一個(gè)數(shù)組。

Array.isArray([]); // true
Array.isArray(Array.prototype); // true

Array.isArray(null); // false
Array.isArray(undefined); // false
Array.isArray(18); // false
Array.isArray("Array"); // false
Array.isArray(true); // false
Array.isArray({ __proto__: Array.prototype });

在公用庫(kù)中,一般會(huì)這么做 isArray 的判斷:

Object.prototype.toString.call(arg) === "[object Array]";
ES6 新增的 Array 操作 1、find 和 findIndex

find() 傳入一個(gè)回調(diào)函數(shù),找到數(shù)組中符合當(dāng)前搜索規(guī)則的第一個(gè)元素,返回這個(gè)元素,并且終止搜索。

const arr = [1, "2", 3, 3, "2"]
console.log(arr.find(n => typeof n === "number")) // 1

findIndex() 與 find() 類似,只是返回的是,找到的這個(gè)元素的下標(biāo)。

const arr = [1, "2", 3, 3, "2"]
console.log(arr.findIndex(n => typeof n === "number")) // 0
2、fill

用指定的元素填充數(shù)組,其實(shí)就是用默認(rèn)內(nèi)容初始化數(shù)組。基本用法:[].fill(value, start, end)

該函數(shù)有三個(gè)參數(shù):填充值(value),填充起始位置(start,可以省略),填充結(jié)束位置(end,可以省略,實(shí)際結(jié)束位置是end-1)。

// 采用一個(gè)默認(rèn)值,填充數(shù)組
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
arr1.fill(7);
console.log(arr1); // [7,7,7,7,7,7,7,7,7,7,7]

// 制定開始和結(jié)束位置填充,實(shí)際填充結(jié)束位置是前一位。
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
arr2.fill(7, 2, 5);
console.log(arr2); // [1,2,7,7,7,6,7,8,9,10,11]

// 結(jié)束位置省略,從起始位置到最后。
const arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
arr3.fill(7, 2);
console.log(arr3); // [1,2,7,7,7,7,7,7,7,7,7]
3、from

將類似數(shù)組的對(duì)象(array-like object)和可遍歷(iterable)的對(duì)象轉(zhuǎn)為真正的數(shù)組。

const set = new Set(1, 2, 3, 3, 4);
Array.from(set)  // [1,2,3,4]

Array.from("foo"); // ["f", "o", "o"]
4、of

Array.of() 方法創(chuàng)建一個(gè)具有可變數(shù)量參數(shù)的新數(shù)組實(shí)例,而不考慮參數(shù)的數(shù)量或類型。

Array.of() 和 Array 構(gòu)造函數(shù)之間的區(qū)別在于處理整數(shù)參數(shù):Array.of(7) 創(chuàng)建一個(gè)具有單個(gè)元素 7 的數(shù)組,而 Array(7) 創(chuàng)建一個(gè)長(zhǎng)度為7的空數(shù)組(注意:這是指一個(gè)有7個(gè)空位的數(shù)組,而不是由7個(gè)undefined組成的數(shù)組)。

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

Array(7);          // [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]
5、copyWithin

選擇數(shù)組的某個(gè)下標(biāo),從該位置開始復(fù)制數(shù)組元素,默認(rèn)從0開始復(fù)制。也可以指定要復(fù)制的元素范圍。基本用法:[].copyWithin(target, start, end)

const arr = [1, 2, 3, 4, 5];
console.log(arr.copyWithin(3));
 // [1,2,3,1,2] 從下標(biāo)為3的元素開始,復(fù)制數(shù)組,所以4, 5被替換成1, 2

const arr1 = [1, 2, 3, 4, 5];
console.log(arr1.copyWithin(3, 1)); 
// [1,2,3,2,3] 從下標(biāo)為3的元素開始,復(fù)制數(shù)組,指定復(fù)制的第一個(gè)元素下標(biāo)為1,所以4, 5被替換成2, 3

const arr2 = [1, 2, 3, 4, 5];
console.log(arr2.copyWithin(3, 1, 2));
// [1,2,3,2,5] 從下標(biāo)為3的元素開始,復(fù)制數(shù)組,指定復(fù)制的第一個(gè)元素下標(biāo)為1,結(jié)束位置為2,所以4被替換成2
6、includes

判斷數(shù)組中是否存在該元素,參數(shù):查找的值、起始位置,可以替換 ES5 時(shí)代的 indexOf 判斷方式。

const arr = [1, 2, 3];
arr.includes(2); // true
arr.includes(4); // false

另外,它還可以用于優(yōu)化 || 的判斷寫法。

if (method === "post" || method === "put" || method === "delete") {
    ...
}

// 用 includes 優(yōu)化 `||` 的寫法
if (["post", "put", "delete"].includes(method)) {
    ...
}
7、entries、values 和 keys

entries() 返回迭代器:返回鍵值對(duì)

//數(shù)組
const arr = ["a", "b", "c"];
for(let v of arr.entries()) {
    console.log(v)
}
// [0, "a"] [1, "b"] [2, "c"]

//Set
const arr = new Set(["a", "b", "c"]);
for(let v of arr.entries()) {
    console.log(v)
}
// ["a", "a"] ["b", "b"] ["c", "c"]

//Map
const arr = new Map();
arr.set("a", "a");
arr.set("b", "b");
for(let v of arr.entries()) {
    console.log(v)
}
// ["a", "a"] ["b", "b"]

values() 返回迭代器:返回鍵值對(duì)的 value

//數(shù)組
const arr = ["a", "b", "c"];
for(let v of arr.values()) {
    console.log(v)
}
//"a" "b" "c"

//Set
const arr = new Set(["a", "b", "c"]);
for(let v of arr.values()) {
    console.log(v)
}
// "a" "b" "c"

//Map
const arr = new Map();
arr.set("a", "a");
arr.set("b", "b");
for(let v of arr.values()) {
    console.log(v)
}
// "a" "b"

keys() 返回迭代器:返回鍵值對(duì)的 key

//數(shù)組
const arr = ["a", "b", "c"];
for(let v of arr.keys()) {
    console.log(v)
}
// 0 1 2

//Set
const arr = new Set(["a", "b", "c"]);
for(let v of arr.keys()) {
    console.log(v)
}
// "a" "b" "c"

//Map
const arr = new Map();
arr.set("a", "a");
arr.set("b", "b");
for(let v of arr.keys()) {
    console.log(v)
}
// "a" "b"
總結(jié)

操作 Array 的數(shù)據(jù)結(jié)構(gòu),在日常工作中會(huì)經(jīng)常遇到。ES6 在 Array 的操作上,也提供了更為簡(jiǎn)便實(shí)用的方法,比如 includes、find、from 等等。

過去,我會(huì)習(xí)慣于用 lodash 的 _.find 方法,現(xiàn)在就可以選擇擁抱原生了。

PS:歡迎關(guān)注我的公眾號(hào) “超哥前端小?!保涣鞲嗟南敕ㄅc技術(shù)。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/109067.html

相關(guān)文章

  • JS 數(shù)組常用API方法遍歷方法總結(jié)

    摘要:數(shù)組語法功能遍歷數(shù)組,返回回調(diào)返回值組成的新數(shù)組,不改變?cè)瓟?shù)組,不會(huì)對(duì)空數(shù)組進(jìn)行檢測(cè)語法功能無法,可以用中來停止,不改變?cè)瓟?shù)組語法功能過濾,返回過濾后的數(shù)組,不改變?cè)瓟?shù)組,不會(huì)對(duì)空數(shù)組進(jìn)行檢測(cè)語法功能有一項(xiàng)返回,則整體為,不改變?cè)瓟?shù)組語法 數(shù)組 (array) ES5 * map 語法:[].map(function(item, index, array) {return xxx})功...

    TNFE 評(píng)論0 收藏0
  • 細(xì)說數(shù)組常用遍歷方法

    摘要:需要返回值,如果不給,默認(rèn)返回使用場(chǎng)景假定有一個(gè)數(shù)值數(shù)組將數(shù)組中的值以雙倍的形式放到數(shù)組寫法方法使用場(chǎng)景假定有一個(gè)對(duì)象數(shù)組將數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到數(shù)組中三從數(shù)組中找出所有符合指定條件的元素檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。 showImg(https://segmentfault.com/img/remote/1460000016810336?w=1149&h=524);...

    阿羅 評(píng)論0 收藏0
  • 細(xì)說數(shù)組常用遍歷方法

    摘要:需要返回值,如果不給,默認(rèn)返回使用場(chǎng)景假定有一個(gè)數(shù)值數(shù)組將數(shù)組中的值以雙倍的形式放到數(shù)組寫法方法使用場(chǎng)景假定有一個(gè)對(duì)象數(shù)組將數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到數(shù)組中三從數(shù)組中找出所有符合指定條件的元素檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。 showImg(https://segmentfault.com/img/remote/1460000016810336?w=1149&h=524);...

    AlphaWatch 評(píng)論0 收藏0
  • 細(xì)說數(shù)組常用遍歷方法

    摘要:需要返回值,如果不給,默認(rèn)返回使用場(chǎng)景假定有一個(gè)數(shù)值數(shù)組將數(shù)組中的值以雙倍的形式放到數(shù)組寫法方法使用場(chǎng)景假定有一個(gè)對(duì)象數(shù)組將數(shù)中對(duì)象某個(gè)屬性的值存儲(chǔ)到數(shù)組中三從數(shù)組中找出所有符合指定條件的元素檢測(cè)數(shù)值元素,并返回符合條件所有元素的數(shù)組。 showImg(https://segmentfault.com/img/remote/1460000016810336?w=1149&h=524);...

    ?xiaoxiao, 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<