來自: https://luoyangfu.com/detail/...前端
最近作項目常常會使用到數組,尤爲在一箇中臺系統中,數組是尤其常見的,並且前端數組能夠實現任何有序數據結構,總結一下數組的方方面面。git
const arr = [] // 直接申明 const arr1 = new Array() // 使用示例構建 const arr2 = Array() const arr3 = Array.of(1, 2) // 從多個參數直接構建一個Array const arr4 = Array.from(likeArr) // 從一個類數組中建立一個數組
上面能夠使用Array.from 進行數組深複製。關於深複製詳見其餘博文github
數組簡單用法
翻譯說: 傳入一個回調函數callback, callback 裏面有三個參數當前遍歷的元素element, 當前元素的座標index, 以及遍歷的數組array. 還有一個可選參數,在find裏面使用this就是這個值thisArg若是未傳入,則是根據當前執行環境獲取this。
express
const a = [1, 2, 4] const value = a.find(current => current > 3) console.log(value) // 4
參數看callback參數,返回結果數組中的符合條件的值,若是是對象則返回對象引用。數組
返回一個array中的值,若是是對象或者數組則返回引用,直接修改會改動數組中的值
遍歷這個數組,可是在forEach中不能夠使用break、continue繼續中斷後續循環, 若是使用return 後將再也不執行return後的語句,也不影響forEach的循環以下圖:
數據結構
複製數組,能夠繼續數組淺拷貝(深拷貝和淺拷貝關注後續)
slice 會複製最外層,類似的好比
使用對象展開符號...
app
slice 傳入兩個可選參數begin
和 end
,返回一個新的數組。以下:
dom
返回一個新數組能夠進行數組的鏈式操做
鏈接一個數組或者多個值:
函數
鏈接一個數組:
ui
返回一個新數組,能夠進行數組的鏈式操做
經過已存在數組進行淺拷貝或者一個類數組的對象轉化成數組:
類數組轉化:
最明顯的類數組,例如查詢頁面dom:
如今是NodeList,轉化成數組:
這樣就能夠使用全部的數組操做
返回的是數組就能夠鏈式使用方法了
將一個值推入到數組的尾端,並返回新的數組長度。
將一個值從數組的尾端移除,並返回移除數組中的那個值.
pop 是 push 的反操做。使用push和pop能夠實現棧數據結構(先進後出)
將一個數據從數組的頭部移除。並返回移除的值
講一個數據添加到數組的頭部,並返回新數組的長度
使用shift和unshift 能夠實現隊列的數據結構(先進先出)
獲取數組中某個值的座標,只能是字面量變量數組,不適用多維數組和多對象數組
有一個可選參數fromIndex,從fromIndex但是搜索
數組進階操做
傳入一個回調函數,會對數組每一個參數執行callback:
polyfill(mdn)
// Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.io/#x15.4.4.19 if (!Array.prototype.map) { Array.prototype.map = function(callback/*, thisArg*/) { var T, A, k; if (this == null) { throw new TypeError('this is null or not defined'); } // 1. Let O be the result of calling ToObject passing the |this| // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal // method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = arguments[1]; } // 6. Let A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor // { Value: mappedValue, // Writable: true, // Enumerable: true, // Configurable: true }, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, k, { // value: mappedValue, // writable: true, // enumerable: true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; }
須要兩個參數,一個callback參數,一個累加初始值.
callback參數:
callback參數有三個累加的值acc, 當前值cv, 當前座標cvIdx, 當前數組arr
用法:
求和:
返回值根據初始化的值來變化,多是數組,對象,數字,字符串等等。
polyfill(mdn)
// Production steps of ECMA-262, Edition 5, 15.4.4.21 // Reference: http://es5.github.io/#x15.4.4.21 // https://tc39.github.io/ecma262/#sec-array.prototype.reduce if (!Array.prototype.reduce) { Object.defineProperty(Array.prototype, 'reduce', { value: function(callback /*, initialValue*/) { if (this === null) { throw new TypeError( 'Array.prototype.reduce ' + 'called on null or undefined' ); } if (typeof callback !== 'function') { throw new TypeError( callback + ' is not a function'); } // 1. Let O be ? ToObject(this value). var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // Steps 3, 4, 5, 6, 7 var k = 0; var value; if (arguments.length >= 2) { value = arguments[1]; } else { while (k < len && !(k in o)) { k++; } // 3. If len is 0 and initialValue is not present, // throw a TypeError exception. if (k >= len) { throw new TypeError( 'Reduce of empty array ' + 'with no initial value' ); } value = o[k++]; } // 8. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kPresent be ? HasProperty(O, Pk). // c. If kPresent is true, then // i. Let kValue be ? Get(O, Pk). // ii. Let accumulator be ? Call( // callbackfn, undefined, // « accumulator, kValue, k, O »). if (k in o) { value = callback(value, o[k], k, o); } // d. Increase k by 1. k++; } // 9. Return accumulator. return value; } }); }
對數組繼續填充,傳入三個變量, 填充值value, 填充開始位置start, 填充結束位置end
返回修改後的數組能夠繼續操做
polyfill(來自mdn)
if (!Array.prototype.fill) { Object.defineProperty(Array.prototype, 'fill', { value: function(value) { // Steps 1-2. if (this == null) { throw new TypeError('this is null or not defined'); } var O = Object(this); // Steps 3-5. var len = O.length >>> 0; // Steps 6-7. var start = arguments[1]; var relativeStart = start >> 0; // Step 8. var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // Steps 9-10. var end = arguments[2]; var relativeEnd = end === undefined ? len : end >> 0; // Step 11. var final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // Step 12. while (k < final) { O[k] = value; k++; } // Step 13. return O; } }); }
判斷是否存在知足回調函數返回的條件,回調函數條件如上callback 參數,返回值是true/false
polyfill(mdn)
if (!Array.prototype.some) { Array.prototype.some = function(fun/*, thisArg*/) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) { return true; } } return false; }; }
判斷數組中每個是否知足回調函數知足的條件,返回true/false
polyfill(mdn)
if (!Array.prototype.every) { Array.prototype.every = function(callbackfn, thisArg) { 'use strict'; var T, k; if (this == null) { throw new TypeError('this is null or not defined'); } // 1. Let O be the result of calling ToObject passing the this // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method // of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== 'function') { throw new TypeError(); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method // of O with argument Pk. kValue = O[k]; // ii. Let testResult be the result of calling the Call internal method // of callbackfn with T as the this value and argument list // containing kValue, k, and O. var testResult = callbackfn.call(T, kValue, k, O); // iii. If ToBoolean(testResult) is false, return false. if (!testResult) { return false; } } k++; } return true; }; }
過濾知足回調函數返回值的的數組,返回值是一個數組,若是沒有知足的則是空數組:
polyfill(mdn)
if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; }
數組中是否包含某個值:
polyfill(mdn)
// https://tc39.github.io/ecma262/#sec-array.prototype.includes if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function(searchElement, fromIndex) { // 1. Let O be ? ToObject(this value). if (this == null) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If len is 0, return false. if (len === 0) { return false; } // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undefined, this step produces the value 0.) var n = fromIndex | 0; // 5. If n ≥ 0, then // a. Let k be n. // 6. Else n < 0, // a. Let k be len + n. // b. If k < 0, let k be 0. var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); function sameValueZero(x, y) { return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); } // 7. Repeat, while k < len while (k < len) { // a. Let elementK be the result of ? Get(O, ! ToString(k)). // b. If SameValueZero(searchElement, elementK) is true, return true. // c. Increase k by 1. if (sameValueZero(o[k], searchElement)) { return true; } k++; } // 8. Return false return false; } }); }
根據回調函數進行排序,參數:
當什麼都不傳遞的時候,則根據每一個字符的Unicode的值
傳入一個比較函數的時候:
這裏描述幾種狀況:
數組的反轉,直接數組頭尾交換:
更換後數組,和變換前數組是同一個對象,同sort函數。
傳入多個變量,將其轉換成新的數組:
map 能夠會數組中每一個值進行相同函數操做,例如:
將一個變量中全部id取出來
var persons = [ { id: 3 }, { id: 4 }] const ids = persons.map(p => p.id)
所謂鏈式操做,就是直接返回數組直接繼續使用數組中方法,不熟悉不推薦使用,代碼維護性降低
以下:
const idsStr = persons.map(p => p.id).join(',') // 3,4(join返回字符串,能夠繼續使用字符串方法)
看以下代碼:
Promise.all(ids.map(id => requestPersonById(id)).then(persons => { // persons 就是每一個id請求的人 })
去重操做:
const arr = [...new Set(duplicateArr)]