亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

JavaScript30秒, 從入門(mén)到放棄之Array(六)

Freeman / 2776人閱讀

摘要:從數(shù)組索引為開(kāi)始刪除元素,直到對(duì)數(shù)組元素運(yùn)用指定方法為為止。對(duì)兩個(gè)數(shù)組的元素分別調(diào)用指定方法后,返回以運(yùn)行結(jié)果為判定基準(zhǔn)的并集,并集是原始數(shù)組元素的并集而不是運(yùn)行結(jié)果的并集。

原文地址:JavaScript30秒, 從入門(mén)到放棄之Array(六)

博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(六)

水平有限,歡迎批評(píng)指正

tail

Returns all elements in an array except for the first one.

Return Array.slice(1) if the array"s length is more than 1, otherwise, return the whole array.

const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);

返回除了數(shù)組第一個(gè)元素以外的所有元素。

如果數(shù)組長(zhǎng)度大于1,則用Array.slice(1)返回;否則返回整個(gè)數(shù)組。

?  code cat tail.js
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);

console.log(tail([1, 2, 3]));
console.log(tail([1]));
?  code node tail.js
[ 2, 3 ]
[ 1 ]
take

Returns an array with n elements removed from the beginning.

Use Array.slice() to create a slice of the array with n elements taken from the beginning.

const take = (arr, n = 1) => arr.slice(0, n);

返回一個(gè)由數(shù)組的前n個(gè)元素組成的新數(shù)組。

Array.slice()創(chuàng)建一個(gè)新的數(shù)組,數(shù)組元素由指定數(shù)組的前n個(gè)元素組成。

?  code cat take.js
const take = (arr, n = 1) => arr.slice(0, n);

console.log(take([1, 2, 3], 5));
console.log(take([1, 2, 3], 0));
?  code node take.js
[ 1, 2, 3 ]
[]

n可以指定為0,即一個(gè)也不取出。省略則n = 1

takeRight

Returns an array with n elements removed from the end.

Use Array.slice() to create a slice of the array with n elements taken from the end.

const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);

返回一個(gè)由數(shù)組的后n個(gè)元素組成的新數(shù)組。

Array.slice()創(chuàng)建一個(gè)新的數(shù)組,數(shù)組元素由指定數(shù)組的后n個(gè)元素組成。

?  code cat takeRight.js
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);

console.log(takeRight([1, 2, 3], 2));
console.log(takeRight([1, 2, 3]));

?  code node takeRight.js
[ 2, 3 ]
[ 3 ]

拿數(shù)組后n個(gè)元素只需從數(shù)組長(zhǎng)度減去n的位置開(kāi)始取到結(jié)尾就可以了,slice第二個(gè)參數(shù)是可以省略的,因?yàn)槭侨〉阶詈笠粋€(gè)元素。

takeRightWhile

Removes elements from the end of an array until the passed function returns true. Returns the removed elements.

Loop through the array, using a for...of loop over Array.keys() until the returned value from the function is true. Return the removed elements, using Array.reverse() and Array.slice().

const takeRightWhile = (arr, func) => {
  for (let i of arr.reverse().keys())
    if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length);
  return arr;
};

從數(shù)組尾部開(kāi)始刪除元素,直到對(duì)數(shù)組元素運(yùn)用指定方法fntrue為止。同時(shí)返回被刪除的元素。

循環(huán)數(shù)組,使用for…of循環(huán)Array.keys()直到對(duì)數(shù)組元素調(diào)用指定方法返回true為止。最后返回刪除的所有元素,過(guò)程中結(jié)合了Array.reverse()Array.slice()。

?  code cat takeRightWhile.js
const takeRightWhile = (arr, func) => {
  for (let i of arr.reverse().keys())
    if(func(arr[i]))
      return arr.reverse().slice(arr.length - i, arr.length);
    return arr;
};

console.log(takeRightWhile([1, 2, 3, 4], n => n < 3));

?  code node takeRightWhile.js
[ 3, 4 ]
for (let i of arr.reverse().keys())

循環(huán)數(shù)組arrkey值,即索引,因?yàn)槭?b>reverse(),所以是反向循環(huán)。如一個(gè)數(shù)組有五個(gè)元素,那么i就是4->3->2->1->0這樣的順序。

if(func(arr[i]))
  return arr.reverse().slice(arr.length - i, arr.length);

對(duì)數(shù)組元素arr[i]調(diào)用func,若真,此時(shí)的i就是順數(shù)的第一個(gè)該刪除的元素的索引,要?jiǎng)h除的元素就是從此直到數(shù)組結(jié)尾為止;即arr.reverse().slice(arr.length - i, arr.length)包含的索引元素。

return arr;

如果前面的整個(gè)遍歷過(guò)程中func(arr[i])都不為true的話,那就返回原數(shù)組,合情合理。

takeWhile

Removes elements in an array until the passed function returns true. Returns the removed elements.

Loop through the array, using a for...of loop over Array.keys() until the returned value from the function is true. Return the removed elements, using Array.slice().

const takeWhile = (arr, func) => {
 for (let i of arr.keys()) if (func(arr[i])) return arr.slice(0, i);
 return arr;
};

從數(shù)組索引為0開(kāi)始刪除元素,直到對(duì)數(shù)組元素運(yùn)用指定方法fntrue為止。同時(shí)返回被刪除的元素。

?  code cat takeWhile.js
const takeWhile = (arr, fn) => {
  for (let i of arr.keys()) if(fn(arr[i])) return arr.slice(0, i);
  return arr;
};

console.log(takeWhile([1, 2, 3, 4], n => n >= 3));

?  code node takeWhile.js
[ 1, 2 ]

takeRightWhile正好相反,而且還更容易理解。沒(méi)什么可說(shuō)的了。

union

Returns every element that exists in any of the two arrays once.

Create a Set with all values of a and b and convert to an array.

const union = (a, b) => Array.from(new Set([...a, ...b]));

返回兩個(gè)數(shù)組的并集(像集合的并集一樣,不包含重復(fù)元素)。

創(chuàng)建一個(gè)以ab數(shù)組為元素的集合并把它轉(zhuǎn)化成數(shù)組。

?  code cat union.js
const union = (a, b) => Array.from(new Set([...a, ...b]));

console.log(union([1, 2, 3], [4, 3, 2]));

?  code node union.js
[ 1, 2, 3, 4 ]

我自己寫(xiě)的如下:

const union = (a, b) => [...new Set([...a, ...b])];

直接用ES6擴(kuò)展運(yùn)算符也能達(dá)到效果。

原理太簡(jiǎn)單,創(chuàng)建ab數(shù)組的集合自然把他們兩者的重復(fù)元素去掉了。

unionBy

Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.

Create a Set by applying all fn to all values of a. Create a Set from a and all elements in b whose value, after applying fn does not match a value in the previously created set. Return the last set converted to an array.

const unionBy = (a, b, fn) => {
  const s = new Set(a.map(v => fn(v)));
  return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))]));
};

對(duì)兩個(gè)數(shù)組的元素分別調(diào)用指定方法后,返回以運(yùn)行結(jié)果為判定基準(zhǔn)的并集,并集是原始數(shù)組元素的并集而不是運(yùn)行結(jié)果的并集。

創(chuàng)建一個(gè)a數(shù)組調(diào)用fn后的集合a1。再創(chuàng)建一個(gè)以數(shù)組a和對(duì)數(shù)組b進(jìn)行過(guò)濾所有存在于集合a1中的元素后所剩余元素組成的數(shù)組為基準(zhǔn)的集合。并把該集合轉(zhuǎn)換成最終的數(shù)組。

?  code cat unionBy.js
const unionBy = (a, b, fn) => {
  const s = new Set(a.map(v => fn(v)));

  return Array.from(new Set([...a, ...b.filter(v => !s.has(fn(v)))]));
};

console.log(unionBy([2.1], [1.2, 2.3], Math.floor));

?  code node unionBy.js
[ 2.1, 1.2 ]
const s = new Set(a.map(v => fn(v)));

首先得創(chuàng)建其中一個(gè)數(shù)組的集合s。

b.filter(v => !s.has(fn(v)))

這里就是把b數(shù)組中所有存在于a調(diào)用fn后生成的集合s的元素都刪除掉。這樣剩下的所有元素和a數(shù)組再進(jìn)行集合運(yùn)算后再轉(zhuǎn)換成數(shù)組。就是我們所需要的結(jié)果。

unionWith

Returns every element that exists in any of the two arrays once, using a provided comparator function.

Create a Set with all values of a and values in b for which the comparator finds no matches in a, using Array.findIndex().

const unionWith = (a, b, comp) =>
  Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));

對(duì)兩個(gè)數(shù)組的元素分別調(diào)用指定比較方法后,返回以運(yùn)行結(jié)果為判定基準(zhǔn)的并集,并集是原始數(shù)組元素的并集而不是運(yùn)行結(jié)果的并集。

?  code cat unionWith.js
const unionWith = (a, b, comp) =>
  Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));

console.log(unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)));

?  code node unionWith.js
[ 1, 1.2, 1.5, 3, 0, 3.9 ]

分主客體,這里主體是前一個(gè)數(shù)組,即a,表示數(shù)組a的所有元素都會(huì)保留下來(lái)。然后循環(huán)數(shù)組b,用findIndex方法去把所有對(duì)ab的元素調(diào)用comp比較方法后的結(jié)果不存在于a數(shù)組中的所有元素篩選出來(lái)。最后把篩選出來(lái)的所有元素和數(shù)組a組成新數(shù)組后再進(jìn)行集合運(yùn)算并把運(yùn)算結(jié)果轉(zhuǎn)化為數(shù)組。那就是unionWith的最終結(jié)果。

uniqueElements

Returns all unique values of an array.

Use ES6 Set and the ...rest operator to discard all duplicated values.

const uniqueElements = arr => [...new Set(arr)];

數(shù)組去重。

?  code cat uniqueElements.js
const uniqueElements = arr => [...new Set(arr)];

console.log(uniqueElements([1, 2, 2, 3, 4, 4, 5]));

?  code node uniqueElements.js
[ 1, 2, 3, 4, 5 ]

結(jié)合ES6的擴(kuò)展運(yùn)算符和集合便很容易實(shí)現(xiàn)。

unzip

Creates an array of arrays, ungrouping the elements in an array produced by zip.

Use Math.max.apply() to get the longest subarray in the array, Array.map() to make each element an array. Use Array.reduce() and Array.forEach() to map grouped values to individual arrays.

const unzip = arr =>
  arr.reduce(
    (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
    Array.from({
      length: Math.max(...arr.map(x => x.length))
    }).map(x => [])
  );

對(duì)于給定的多個(gè)數(shù)組,返回一個(gè)新的二維數(shù)組,數(shù)組的第一個(gè)元素包含多個(gè)數(shù)組的第一個(gè)元素,數(shù)組的第二個(gè)元素包含多個(gè)數(shù)組的第二個(gè)元素,以此類(lèi)推(即把zip方法分好組的數(shù)組逆向解組)。

使用Math.max.apply()方法來(lái)獲取輸入數(shù)組的子數(shù)組元素個(gè)數(shù)的最大長(zhǎng)度,使用Array.map()來(lái)把每一個(gè)元素創(chuàng)建成一個(gè)數(shù)組。然后使用Array.reduce()Array.forEach()去把組里的元素分別加到各自的數(shù)組中。

?  code cat unzip.js
const unzip = arr =>
  arr.reduce((acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
    Array.from({
      length: Math.max(...arr.map(x => x.length))
    }).map(x => [])
  );

console.log(unzip([["a", 1, true], ["b", 2, false]]));
console.log(unzip([["a", 1, true], ["b", 2]]));

?  code node unzip.js
[ [ "a", "b" ], [ 1, 2 ], [ true, false ] ]
[ [ "a", "b" ], [ 1, 2 ], [ true ] ]
Array.from({
  length: Math.max(...arr.map(x => x.length))
}).map(x => [])

這就是reduce的初始二維數(shù)組,用Array.from來(lái)生成一個(gè)數(shù)組,然后再map(x => [])成一個(gè)二維數(shù)組,那么數(shù)組的長(zhǎng)度怎么定呢?因?yàn)楸?b>unzip的原數(shù)組里的元素可能是長(zhǎng)度不同的數(shù)組。那么肯定是以長(zhǎng)度最長(zhǎng)的那個(gè)為準(zhǔn),這樣才能包含解組后的所有元素。這就是length: Math.max(...arr.map(x => x.length))做的事。

對(duì)于reduce里的方法:

(acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc)

acc是累加值,在遍歷過(guò)程中會(huì)一直變化,val.forEach((v, i) => acc[i].push(v))這是遍歷過(guò)程中val數(shù)組元素push到累加acc對(duì)應(yīng)索引數(shù)組的方法。

舉個(gè)例子:

原數(shù)組arr = [[1, 2, 3], ["a", "b"]],在遍歷過(guò)程中初始累加acc = [[], [], []](含有三個(gè)元素的數(shù)組)。

// 第一次
val = [1, 2, 3]
acc = [[1], [2], [3]]

// 第二次
val = ["a", "b"]
acc = [[1, "a"], [2, "b"], [3]] // 這也是最終結(jié)果
unzipWith

Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.

Use Math.max.apply() to get the longest subarray in the array, Array.map() to make each element an array. Use Array.reduce() and Array.forEach() to map grouped values to individual arrays. Use Array.map() and the spread operator (...) to apply fn to each individual group of elements.

const unzipWith = (arr, fn) =>
  arr
    .reduce(
      (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
      Array.from({
        length: Math.max(...arr.map(x => x.length))
      }).map(x => [])
    )
    .map(val => fn(...val));

對(duì)于給定的多個(gè)數(shù)組,返回一個(gè)新的二維數(shù)組,數(shù)組的第一個(gè)元素包含多個(gè)數(shù)組的第一個(gè)元素,數(shù)組的第二個(gè)元素包含多個(gè)數(shù)組的第二個(gè)元素,以此類(lèi)推(即把zip方法分好組的數(shù)組逆向解組),在此基礎(chǔ)上對(duì)二維數(shù)組的每個(gè)元素運(yùn)行指定方法并返回。

使用Math.max.apply()方法來(lái)獲取數(shù)組的子數(shù)組元素個(gè)數(shù)的最大長(zhǎng)度,使用Array.map()來(lái)把每一個(gè)元素創(chuàng)建成一個(gè)數(shù)組。然后使用Array.reduce()Array.forEach()去把組里的元素分別加到各自的數(shù)組中。然后再結(jié)合 Array.map()和ES6擴(kuò)展運(yùn)算符把前面生成的二維數(shù)組的每個(gè)元素分別調(diào)用fn方法。

?  code cat unzipWith.js
const unzipWith = (arr, fn) =>
    arr.reduce((acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
        Array.from({
            length: Math.max(...arr.map(x => x.length))
        }).map(x => [])
    )
    .map(val => fn(...val));

console.log(unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)));

?  code node unzipWith.js
[ 3, 30, 300 ]

unzipWith就比unzip多了一個(gè)對(duì)每個(gè)二維數(shù)組元素調(diào)用指定fn方法。即map(val => fn(...val))。其它都和unzip一樣,沒(méi)啥可說(shuō)的了??匆陨侠舆\(yùn)行結(jié)果就知道了。

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

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

相關(guān)文章

  • JavaScript30, 入門(mén)放棄Array(二)

    摘要:循環(huán)一個(gè)數(shù)組,使用每次去刪除該數(shù)組的第一個(gè)元素直到指定方法運(yùn)算結(jié)果為,返回的是剩余元素組成的數(shù)組。直到循環(huán)退出,返回此時(shí)的。對(duì)應(yīng)就是,包含下界,不包含上屆。秒,從入門(mén)到放棄之二微信公眾號(hào)秒,從入門(mén)到放棄之二 difference Returns the difference between two arrays. Create a Set from b, then use Array...

    pinecone 評(píng)論0 收藏0
  • JavaScript30, 入門(mén)放棄Array(五)

    摘要:原文地址秒,從入門(mén)到放棄之五博客地址秒,從入門(mén)到放棄之五水平有限,歡迎批評(píng)指正從給定的數(shù)組中隨機(jī)選出指定個(gè)數(shù)的數(shù)組元素。否則判斷數(shù)組元素是否大于或者等于指定元素,尋找過(guò)程與前邊類(lèi)似。 原文地址:JavaScript30秒, 從入門(mén)到放棄之Array(五)博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(五) 水平有限,歡迎批評(píng)指正 sampleSize Gets n...

    dunizb 評(píng)論0 收藏0
  • JavaScript30入門(mén)放棄Array(三)

    摘要:否則,直接循環(huán)去拼接該值返回按照指定的方法對(duì)數(shù)組元素進(jìn)行分組歸類(lèi)。使用創(chuàng)建一個(gè)對(duì)象,對(duì)象的鍵是生成的結(jié)果,值是符合該鍵的所有數(shù)組元素組成的數(shù)組。微信公眾號(hào)秒,從入門(mén)到放棄之三 原文鏈接:JavaScript30秒, 從入門(mén)到放棄之Array(三)水平有限,歡迎批評(píng)指正 flattenDepth Flattens an array up to the specified depth....

    FrancisSoung 評(píng)論0 收藏0
  • JavaScript30, 入門(mén)放棄Array(七)

    摘要:地址秒,從入門(mén)到放棄之七博客地址秒,從入門(mén)到放棄之七水平有限,歡迎批評(píng)指正剔除掉數(shù)組中所有存在于所指定的元素們的項(xiàng)。使用,和來(lái)創(chuàng)建由兩個(gè)數(shù)組元素拼接而成的所有可能對(duì)并將它們存在一個(gè)數(shù)組中的數(shù)組。 GitHub地址:JavaScript30秒, 從入門(mén)到放棄之Array(七)博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(七) 水平有限,歡迎批評(píng)指正 without ...

    Cciradih 評(píng)論0 收藏0
  • JavaScript30入門(mén)放棄

    摘要:三元運(yùn)算符遍歷過(guò)程中判斷遍歷數(shù)組值是否嚴(yán)格等于指定值,是,次數(shù)否,。三元運(yùn)算符判斷是否是一個(gè)數(shù)組,是,返回遞歸運(yùn)用后的值否,直接返回。秒,從入門(mén)到放棄博客地址秒,從入門(mén)到放棄微信公眾號(hào)地址秒,從入門(mén)到放棄 有意思 最近很火的github上的庫(kù)30-seconds-of-code,特別有意思,代碼也很優(yōu)雅。 能學(xué)es6 自己翻譯,能學(xué)英語(yǔ) 代碼很美,很優(yōu)雅,美即正義 函數(shù)式表達(dá),享受 ...

    TNFE 評(píng)論0 收藏0

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

0條評(píng)論

Freeman

|高級(jí)講師

TA的文章

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