<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                ### 1. 擴展運算符 含義 擴展運算符(spread)是三個點(...)。它好比 rest 參數的逆運算,將一個數組轉為用逗號分隔的參數序列。 ~~~ console.log(...[1, 2, 3]) // 1 2 3 console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5 [...document.querySelectorAll('div')] // [<div>, <div>, <div>] // 該運算符主要用于函數調用。 function push(array, ...items) { array.push(...items); } function add(x, y) { return x + y; } const numbers = [4, 38]; add(...numbers) // 42 ~~~ 上面代碼中,`array.push(...items)和add(...numbers)`這兩行,都是函數的調用,它們的都使用了擴展運算符。該運算符將一個數組,變為參數序列。 擴展運算符與正常的函數參數可以結合使用,非常靈活。 ~~~ function f(v, w, x, y, z) { } const args = [0, 1]; f(-1, ...args, 2, ...[3]); ~~~ 擴展運算符后面還可以放置表達式。 ~~~ const arr = [ ...(x > 0 ? ['a'] : []), 'b', ]; ~~~ 如果擴展運算符后面是一個空數組,則不產生任何效果。 ~~~ [...[], 1] // [1] ~~~ 替代函數的 apply 方法 由于擴展運算符可以展開數組,所以不再需要apply方法,將數組轉為函數的參數了。 ~~~ // ES5 的寫法 function f(x, y, z) { // ... } var args = [0, 1, 2]; f.apply(null, args); // ES6的寫法 function f(x, y, z) { // ... } let args = [0, 1, 2]; f(...args); ~~~ 下面是擴展運算符取代apply方法的一個實際的例子,應用Math.max方法,簡化求出一個數組最大元素的寫法。 ~~~ // ES5 的寫法 Math.max.apply(null, [14, 3, 77]) // ES6 的寫法 Math.max(...[14, 3, 77]) // 等同于 Math.max(14, 3, 77); ~~~ 上面代碼中,由于 JavaScript 不提供求數組最大元素的函數,所以只能套用Math.max函數,將數組轉為一個參數序列,然后求最大值。有了擴展運算符以后,就可以直接用Math.max了。 另一個例子是通過push函數,將一個數組添加到另一個數組的尾部。 ~~~ // ES5的 寫法 var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; Array.prototype.push.apply(arr1, arr2); // ES6 的寫法 let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; arr1.push(...arr2); ~~~ 上面代碼的 ES5 寫法中,push方法的參數不能是數組,所以只好通過apply方法變通使用push方法。有了擴展運算符,就可以直接將數組傳入push方法。 下面是另外一個例子。 ~~~ // ES5 new (Date.bind.apply(Date, [null, 2015, 1, 1])) // ES6 new Date(...[2015, 1, 1]); ~~~ ### 2. 擴展運算符的應用 (1)復制數組 數組是復合的數據類型,直接復制的話,只是復制了指向底層數據結構的指針,而不是克隆一個全新的數組。 ~~~ const a1 = [1, 2]; const a2 = a1; a2[0] = 2; a1 // [2, 2] ~~~ 上面代碼中,a2并不是a1的克隆,*而是指向同一份數據的另一個指針* 修改a2,會直接導致a1的變化。 ES5 只能用變通方法來復制數組。 ~~~ const a1 = [1, 2]; const a2 = a1.concat(); a2[0] = 2; a1 // [1, 2] ~~~ 上面代碼中,a1會返回原數組的克隆,再修改a2就不會對a1產生影響。 擴展運算符提供了復制數組的簡便寫法。 ~~~ const a1 = [1, 2]; // 寫法一 const a2 = [...a1]; // 寫法二 const [...a2] = a1; 上面的兩種寫法,a2都是a1的克隆。 ~~~ (2)合并數組 擴展運算符提供了數組合并的新寫法。 ~~~ const arr1 = ['a', 'b']; const arr2 = ['c']; const arr3 = ['d', 'e']; // ES5 的合并數組 arr1.concat(arr2, arr3); // [ 'a', 'b', 'c', 'd', 'e' ] // ES6 的合并數組 [...arr1, ...arr2, ...arr3] // [ 'a', 'b', 'c', 'd', 'e' ] ~~~ 不過,這兩種方法都是淺拷貝,使用的時候需要注意。 ~~~ const a1 = [{ foo: 1 }]; const a2 = [{ bar: 2 }]; const a3 = a1.concat(a2); const a4 = [...a1, ...a2]; a3[0] === a1[0] // true a4[0] === a1[0] // true ~~~ 上面代碼中,a3和a4是用兩種不同方法合并而成的新數組,但是它們的成員都是對原數組成員的引用,這就是淺拷貝。如果修改了原數組的成員,會同步反映到新數組。 (3)與解構賦值結合 擴展運算符可以與解構賦值結合起來,用于生成數組。 ~~~ // ES5 a = list[0], rest = list.slice(1) // ES6 [a, ...rest] = list ~~~ 下面是另外一些例子。 ~~~ const [first, ...rest] = [1, 2, 3, 4, 5]; first // 1 rest // [2, 3, 4, 5] const [first, ...rest] = []; first // undefined rest // [] const [first, ...rest] = ["foo"]; first // "foo" rest // [] ~~~ > **如果將擴展運算符用于數組賦值,只能放在參數的最后一位,否則會報錯。** ~~~ const [...butLast, last] = [1, 2, 3, 4, 5]; // 報錯 const [first, ...middle, last] = [1, 2, 3, 4, 5]; // 報錯 ~~~ (4)字符串 擴展運算符還可以將字符串轉為真正的數組。 ~~~ [...'hello'] // [ "h", "e", "l", "l", "o" ] ~~~ 上面的寫法,有一個重要的好處,那就是能夠正確識別四個字節的 Unicode 字符。 ~~~ 'x\uD83D\uDE80y'.length // 4 [...'x\uD83D\uDE80y'].length // 3 ~~~ 上面代碼的第一種寫法,JavaScript 會將四個字節的 Unicode 字符,識別為 2 個字符,采用擴展運算符就沒有這個問題。因此,正確返回字符串長度的函數,可以像下面這樣寫。 ~~~ function length(str) { return [...str].length; } length('x\uD83D\uDE80y') // 3 ~~~ 凡是涉及到操作四個字節的 Unicode 字符的函數,都有這個問題。因此,最好都用擴展運算符改寫。 ~~~ let str = 'x\uD83D\uDE80y'; str.split('').reverse().join('') // 'y\uDE80\uD83Dx' [...str].reverse().join('') // 'y\uD83D\uDE80x' ~~~ 上面代碼中,如果不用擴展運算符,字符串的reverse操作就不正確。 (5)實現了 Iterator 接口的對象 任何 Iterator 接口的對象(參閱 Iterator 一章),都可以用擴展運算符轉為真正的數組。 ~~~ let nodeList = document.querySelectorAll('div'); let array = [...nodeList]; ~~~ 上面代碼中,querySelectorAll方法返回的是一個nodeList對象。它不是數組,而是一個類似數組的對象。這時,擴展運算符可以將其轉為真正的數組,原因就在于NodeList對象實現了 Iterator 。 對于那些沒有部署 Iterator 接口的類似數組的對象,擴展運算符就無法將其轉為真正的數組。 ~~~ let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; // TypeError: Cannot spread non-iterable object. let arr = [...arrayLike]; ~~~ 上面代碼中,arrayLike是一個類似數組的對象,但是沒有部署 Iterator 接口,擴展運算符就會報錯。這時,可以改為使用Array.from方法將arrayLike轉為真正的數組。 (6)Map 和 Set 結構,Generator 函數 擴展運算符內部調用的是數據結構的 Iterator 接口,因此只要具有 Iterator 接口的對象,都可以使用擴展運算符,比如 Map 結構。 ~~~ 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] ~~~ 上面代碼中,變量go是一個 Generator 函數,執行后返回的是一個遍歷器對象,對這個遍歷器對象執行擴展運算符,就會將內部遍歷得到的值,轉為一個數組。 如果對沒有 Iterator 接口的對象,使用擴展運算符,將會報錯。 ~~~ const obj = {a: 1, b: 2}; let arr = [...obj]; // TypeError: Cannot spread non-iterable object ~~~ ### 3. Array.from() Array.from方法用于將兩類對象轉為真正的數組:類似數組的對象(array-like object)和可遍歷(iterable)的對象(包括 ES6 新增的數據結構 Set 和 Map)。 下面是一個類似數組的對象,Array.from將它轉為真正的數組。 ~~~ let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; // ES5的寫法 var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c'] // ES6的寫法 let arr2 = Array.from(arrayLike); // ['a', 'b', 'c'] ~~~ 實際應用中,常見的類似數組的對象是 DOM 操作返回的 NodeList 集合,以及函數內部的arguments對象。Array.from都可以將它們轉為真正的數組。 ~~~ // NodeList對象 let ps = document.querySelectorAll('p'); Array.from(ps).filter(p => { return p.textContent.length > 100; }); // arguments對象 function foo() { var args = Array.from(arguments); // ... } ~~~ 上面代碼中,querySelectorAll方法返回的是一個類似數組的對象,可以將這個對象轉為真正的數組,再使用filter方法。 只要是部署了 Iterator 接口的數據結構,Array.from都能將其轉為數組。 ~~~ Array.from('hello') // ['h', 'e', 'l', 'l', 'o'] let namesSet = new Set(['a', 'b']) Array.from(namesSet) // ['a', 'b'] ~~~ 上面代碼中,字符串和 Set 結構都具有 Iterator 接口,因此可以被Array.from轉為真正的數組。 如果參數是一個真正的數組,Array.from會返回一個一模一樣的新數組。 ~~~ Array.from([1, 2, 3]) // [1, 2, 3] ~~~ 值得提醒的是,擴展運算符(...)也可以將某些數據結構轉為數組。 ~~~ // arguments對象 function foo() { const args = [...arguments]; } // NodeList對象 [...document.querySelectorAll('div')] ~~~ 擴展運算符背后調用的是遍歷器接口(Symbol.iterator),如果一個對象沒有部署這個接口,就無法轉換。Array.from方法還支持類似數組的對象。所謂類似數組的對象,本質特征只有一點,即必須有length屬性。因此,任何有length屬性的對象,都可以通過Array.from方法轉為數組,而此時擴展運算符就無法轉換。 ~~~ Array.from({ length: 3 }); // [ undefined, undefined, undefined ] ~~~ 上面代碼中,Array.from返回了一個具有三個成員的數組,每個位置的值都是undefined。擴展運算符轉換不了這個對象。 對于還沒有部署該方法的瀏覽器,可以用Array.prototype.slice方法替代。 ~~~ const toArray = (() => Array.from ? Array.from : obj => [].slice.call(obj) )(); ~~~ Array.from還可以接受第二個參數,作用類似于數組的map方法,用來對每個元素進行處理,將處理后的值放入返回的數組。 ~~~ Array.from(arrayLike, x => x * x); // 等同于 Array.from(arrayLike).map(x => x * x); Array.from([1, 2, 3], (x) => x * x) // [1, 4, 9] ~~~ 下面的例子是取出一組 DOM 節點的文本內容。 ~~~ let spans = document.querySelectorAll('span.name'); // map() let names1 = Array.prototype.map.call(spans, s => s.textContent); // Array.from() let names2 = Array.from(spans, s => s.textContent) ~~~ 下面的例子將數組中布爾值為false的成員轉為0。 ~~~ Array.from([1, , 2, , 3], (n) => n || 0) // [1, 0, 2, 0, 3] ~~~ 另一個例子是返回各種數據的類型。 ~~~ function typesOf () { return Array.from(arguments, value => typeof value) } typesOf(null, [], NaN) // ['object', 'object', 'number'] ~~~ 如果map函數里面用到了this關鍵字,還可以傳入Array.from的第三個參數,用來綁定this。 Array.from()可以將各種值轉為真正的數組,并且還提供map功能。這實際上意味著,只要有一個原始的數據結構,你就可以先對它的值進行處理,然后轉成規范的數組結構,進而就可以使用數量眾多的數組方法。 ~~~ Array.from({ length: 2 }, () => 'jack') // ['jack', 'jack'] ~~~ 上面代碼中,Array.from的第一個參數指定了第二個參數運行的次數。這種特性可以讓該方法的用法變得非常靈活。 Array.from()的另一個應用是,將字符串轉為數組,然后返回字符串的長度。因為它能正確處理各種 Unicode 字符,可以避免 JavaScript 將大于\uFFFF的 Unicode 字符,算作兩個字符的 bug。 ~~~ function countSymbols(string) { return Array.from(string).length; } ~~~ ### 5. Array.of() **Array.of方法用于將一組值,轉換為數組。** ~~~ Array.of(3, 11, 8) // [3,11,8] Array.of(3) // [3] Array.of(3).length // 1 ~~~ 這個方法的主要目的,是彌補數組構造函數Array()的不足。因為參數個數的不同,會導致Array()的行為有差異。 ~~~ Array() // [] Array(3) // [, , ,] Array(3, 11, 8) // [3, 11, 8] ~~~ 上面代碼中,Array方法沒有參數、一個參數、三個參數時,返回結果都不一樣。只有當參數個數不少于 2 個時,Array()才會返回由參數組成的新數組。參數個數只有一個時,實際上是指定數組的長度。 Array.of基本上可以用來替代Array()或new Array(),并且不存在由于參數不同而導致的重載。它的行為非常統一。 ~~~ Array.of() // [] Array.of(undefined) // [undefined] Array.of(1) // [1] Array.of(1, 2) // [1, 2] ~~~ Array.of總是返回參數值組成的數組。如果沒有參數,就返回一個空數組。 Array.of方法可以用下面的代碼模擬實現。 ~~~ function ArrayOf(){ return [].slice.call(arguments); } ~~~ ### 6. 數組實例的 copyWithin() 數組實例的copyWithin方法,在當前數組內部,將指定位置的成員復制到其他位置(會覆蓋原有成員),然后返回當前數組。也就是說,使用這個方法,會修改當前數組。 `Array.prototype.copyWithin(target, start = 0, end = this.length)` 它接受三個參數。 target(必需):從該位置開始替換數據。如果為負值,表示倒數。 start(可選):從該位置開始讀取數據,默認為 0。如果為負值,表示倒數。 end(可選):到該位置前停止讀取數據,默認等于數組長度。如果為負值,表示倒數。 這三個參數都應該是數值,如果不是,會自動轉為數值。 ~~~ [1, 2, 3, 4, 5].copyWithin(0, 3) // [4, 5, 3, 4, 5] ~~~ 上面代碼表示將從 3 號位直到數組結束的成員(4 和 5),復制到從 0 號位開始的位置,結果覆蓋了原來的 1 和 2。 下面是更多例子。 ~~~ // 將3號位復制到0號位 [1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5] // -2相當于3號位,-1相當于4號位 [1, 2, 3, 4, 5].copyWithin(0, -2, -1) // [4, 2, 3, 4, 5] // 將3號位復制到0號位 [].copyWithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // 將2號位到數組結束,復制到0號位 let i32a = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5] // 對于沒有部署 TypedArray 的 copyWithin 方法的平臺 // 需要采用下面的寫法 [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5] ~~~ ### 7.數組實例的 find() 和 findIndex() 數組實例的find方法,用于找出第一個符合條件的數組成員。它的參數是一個回調函數,所有數組成員依次執行該回調函數,直到找出第一個返回值為true的成員,然后返回該成員。如果沒有符合條件的成員,則返回undefined。 ~~~ [1, 4, -5, 10].find((n) => n < 0) // -5 ~~~ 上面代碼找出數組中第一個小于 0 的成員。 ~~~ [1, 5, 10, 15].find(function(value, index, arr) { return value > 9; }) // 10 ~~~ 上面代碼中,find方法的回調函數可以接受三個參數,依次為當前的值、當前的位置和原數組。 數組實例的findIndex方法的用法與find方法非常類似,返回第一個符合條件的數組成員的位置,如果所有成員都不符合條件,則返回-1。 ~~~ [1, 5, 10, 15].findIndex(function(value, index, arr) { return value > 9; }) // 2 ~~~ 這兩個方法都可以接受第二個參數,用來綁定回調函數的this對象。 ~~~ function f(v){ return v > this.age; } let person = {name: 'John', age: 20}; [10, 12, 26, 15].find(f, person); // 26 ~~~ 上面的代碼中,find函數接收了第二個參數person對象,回調函數中的this對象指向person對象。 另外,這兩個方法都可以發現NaN,彌補了數組的indexOf方法的不足。 ~~~ [NaN].indexOf(NaN) // -1 [NaN].findIndex(y => Object.is(NaN, y)) // 0 ~~~ 上面代碼中,indexOf方法無法識別數組的NaN成員,但是findIndex方法可以借助Object.is方法做到。 ### 8.數組實例的 fill() fill方法使用給定值,填充一個數組。 ~~~ ['a', 'b', 'c'].fill(7) // [7, 7, 7] new Array(3).fill(7) // [7, 7, 7] ~~~ > 上面代碼表明,fill方法用于空數組的初始化非常方便。數組中已有的元素,會被全部抹去。 fill方法還可以接受第二個和第三個參數,用于指定填充的起始位置和結束位置。 ~~~ ['a', 'b', 'c'].fill(7, 1, 2) // ['a', 7, 'c'] ~~~ 上面代碼表示,fill方法從 1 號位開始,向原數組填充 7,到 2 號位之前結束。 注意,如果填充的類型為對象,那么被賦值的是同一個內存地址的對象,而不是深拷貝對象。 ~~~ let arr = new Array(3).fill({name: "Mike"}); arr[0].name = "Ben"; arr // [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}] let arr = new Array(3).fill([]); arr[0].push(5); arr // [[5], [5], [5]] ~~~ ### 9.數組實例的 entries(),keys() 和 values() ES6 提供三個新的方法——entries(),keys()和values()——用于遍歷數組。它們都返回一個遍歷器對象(詳見《Iterator》一章),可以用for...of循環進行遍歷,唯一的區別是keys()是對鍵名的遍歷、values()是對鍵值的遍歷,entries()是對鍵值對的遍歷。 ~~~ for (let index of ['a', 'b'].keys()) { console.log(index); } // 0 // 1 for (let elem of ['a', 'b'].values()) { console.log(elem); } // 'a' // 'b' for (let [index, elem] of ['a', 'b'].entries()) { console.log(index, elem); } // 0 "a" // 1 "b" ~~~ 如果不使用for...of循環,可以手動調用遍歷器對象的next方法,進行遍歷。 ~~~ let letter = ['a', 'b', 'c']; let entries = letter.entries(); console.log(entries.next().value); // [0, 'a'] console.log(entries.next().value); // [1, 'b'] console.log(entries.next().value); // [2, 'c'] ~~~ ### 10. 數組實例的 includes() Array.prototype.includes方法返回一個布爾值,表示某個數組是否包含給定的值,與字符串的includes方法類似。ES2016 引入了該方法。 ~~~ [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, NaN].includes(NaN) // true ~~~ 該方法的第二個參數表示搜索的起始位置,默認為0。如果第二個參數為負數,則表示倒數的位置,如果這時它大于數組長度(比如第二個參數為-4,但數組長度為3),則會重置為從0開始。 ~~~ [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true ~~~ 沒有該方法之前,我們通常使用數組的indexOf方法,檢查是否包含某個值。 ~~~ if (arr.indexOf(el) !== -1) { // ... } ~~~ indexOf方法有兩個缺點,一是不夠語義化,它的含義是找到參數值的第一個出現位置,所以要去比較是否不等于-1,表達起來不夠直觀。二是,它內部使用嚴格相等運算符(===)進行判斷,這會導致對NaN的誤判。 ~~~ [NaN].indexOf(NaN) // -1 ~~~ includes使用的是不一樣的判斷算法,就沒有這個問題。 ~~~ [NaN].includes(NaN) // true ~~~ 下面代碼用來檢查當前環境是否支持該方法,如果不支持,部署一個簡易的替代版本。 ~~~ const contains = (() => Array.prototype.includes ? (arr, value) => arr.includes(value) : (arr, value) => arr.some(el => el === value) )(); contains(['foo', 'bar'], 'baz'); // => false ~~~ 另外,Map 和 Set 數據結構有一個has方法,需要注意與includes區分。 ~~~ Map 結構的has方法,是用來查找鍵名的, 比如Map.prototype.has(key)、WeakMap.prototype.has(key)、 Reflect.has(target, propertyKey)。 ~~~ ~~~ Set 結構的has方法,是用來查找值的, 比如Set.prototype.has(value)、WeakSet.prototype.has(value)。 ~~~ ### 11. 數組實例的 flat(),flatMap() 數組的成員有時還是數組,Array.prototype.flat()用于將嵌套的數組“拉平”,變成一維的數組。該方法返回一個新數組,對原數據沒有影響。 ~~~ [1, 2, [3, 4]].flat() // [1, 2, 3, 4] ~~~ 上面代碼中,原數組的成員里面有一個數組,flat()方法將子數組的成員取出來,添加在原來的位置。 flat()默認只會“拉平”一層,如果想要“拉平”多層的嵌套數組,可以將flat()方法的參數寫成一個整數,表示想要拉平的層數,默認為1。 ~~~ [1, 2, [3, [4, 5]]].flat() // [1, 2, 3, [4, 5]] [1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5] ~~~ 上面代碼中,flat()的參數為2,表示要“拉平”兩層的嵌套數組。 * 如果不管有多少層嵌套,都要轉成一維數組,可以用Infinity關鍵字作為參數。 ~~~ [1, [2, [3]]].flat(Infinity) // [1, 2, 3] ~~~ * 如果原數組有空位,flat()方法會跳過空位。 ~~~ [1, 2, , 4, 5].flat() // [1, 2, 4, 5] ~~~ flatMap()方法對原數組的每個成員執行一個函數(相當于執行Array.prototype.map()),然后對返回值組成的數組執行flat()方法。該方法返回一個新數組,不改變原數組。 ~~~ // 相當于 [[2, 4], [3, 6], [4, 8]].flat() [2, 3, 4].flatMap((x) => [x, x * 2]) // [2, 4, 3, 6, 4, 8] ~~~ flatMap()只能展開一層數組。 ~~~ // 相當于 [[[2]], [[4]], [[6]], [[8]]].flat() [1, 2, 3, 4].flatMap(x => [[x * x]]) // [[2], [4], [6], [8]] ~~~ 上面代碼中,遍歷函數返回的是一個雙層的數組,但是默認只能展開一層,因此flatMap()返回的還是一個嵌套數組。 flatMap()方法的參數是一個遍歷函數,該函數可以接受三個參數,分別是當前數組成員、當前數組成員的位置(從零開始)、原數組。 ~~~ arr.flatMap(function callback(currentValue[, index[, array]]) { // ... }[, thisArg]) ~~~ flatMap()方法還可以有第二個參數,用來綁定遍歷函數里面的this。 ### 12. 數組的空位 數組的空位指,數組的某一個位置沒有任何值。比如,Array構造函數返回的數組都是空位。 `Array(3) // [, , ,]` 上面代碼中,Array(3)返回一個具有 3 個空位的數組。 注意,空位不是undefined,一個位置的值等于undefined,依然是有值的。空位是沒有任何值,in運算符可以說明這一點。 ~~~ 0 in [undefined, undefined, undefined] // true 0 in [, , ,] // false ~~~ 上面代碼說明,第一個數組的 0 號位置是有值的,第二個數組的 0 號位置沒有值。 ES5 對空位的處理,已經很不一致了,大多數情況下會忽略空位。 forEach(), filter(), reduce(), every() 和some()都會跳過空位。 map()會跳過空位,但會保留這個值 join()和toString()會將空位視為undefined,而undefined和null會被處理成空字符串。 ~~~ // forEach方法 [,'a'].forEach((x,i) => console.log(i)); // 1 // filter方法 ['a',,'b'].filter(x => true) // ['a','b'] // every方法 [,'a'].every(x => x==='a') // true // reduce方法 [1,,2].reduce((x,y) => x+y) // 3 // some方法 [,'a'].some(x => x !== 'a') // false // map方法 [,'a'].map(x => 1) // [,1] // join方法 [,'a',undefined,null].join('#') // "#a##" // toString方法 [,'a',undefined,null].toString() // ",a,," ~~~ ES6 則是明確將空位轉為undefined。 Array.from方法會將數組的空位,轉為undefined,也就是說,這個方法不會忽略空位。 ~~~ Array.from(['a',,'b']) // [ "a", undefined, "b" ] 擴展運算符(...)也會將空位轉為undefined。 [...['a',,'b']] // [ "a", undefined, "b" ] ~~~ copyWithin()會連空位一起拷貝。 ~~~ [,'a','b',,].copyWithin(2,0) // [,"a",,"a"] ~~~ fill()會將空位視為正常的數組位置。 ~~~ new Array(3).fill('a') // ["a","a","a"] for...of循環也會遍歷空位。 let arr = [, ,]; for (let i of arr) { console.log(1); } // 1 // 1 ~~~ 上面代碼中,數組arr有兩個空位,for...of并沒有忽略它們。如果改成map方法遍歷,空位是會跳過的。 entries()、keys()、values()、find()和findIndex()會將空位處理成undefined。 ~~~ // entries() [...[,'a'].entries()] // [[0,undefined], [1,"a"]] // keys() [...[,'a'].keys()] // [0,1] // values() [...[,'a'].values()] // [undefined,"a"] // find() [,'a'].find(x => true) // undefined // findIndex() [,'a'].findIndex(x => true) // 0 ~~~ 由于空位的處理規則非常不統一,所以建議避免出現空位。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看