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

資訊專欄INFORMATION COLUMN

JavaScript30秒, 從入門到放棄之Array(七)

Cciradih / 3298人閱讀

摘要:地址秒,從入門到放棄之七博客地址秒,從入門到放棄之七水平有限,歡迎批評指正剔除掉數(shù)組中所有存在于所指定的元素們的項。使用,和來創(chuàng)建由兩個數(shù)組元素拼接而成的所有可能對并將它們存在一個數(shù)組中的數(shù)組。

GitHub地址:JavaScript30秒, 從入門到放棄之Array(七)

博客地址:JavaScript30秒, 從入門到放棄之Array(七)

水平有限,歡迎批評指正

without

Filters out the elements of an array, that have one of the specified values.

Use Array.filter() to create an array excluding(using !Array.includes()) all given values.

const without = (arr, ...args) => arr.filter(v => !args.includes(v));

剔除掉數(shù)組中所有存在于所指定的元素們的項。

使用Array.filter()創(chuàng)建一個將所有提供的值排除在外(使用!Array.includes())的數(shù)組。

?  code cat without.js
const without = (arr, ...args) => arr.filter(v => !args.includes(v));

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

filterincludes結(jié)合,把數(shù)組arr中所有存在于指定的元素值…args中的項排除在外,很清爽干凈。

xProd

Creates a new array out of the two supplied by creating each possible pair from the arrays.

Use Array.reduce(), Array.map() and Array.concat() to produce every possible pair from the elements of the two arrays and save them in an array.

const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);

創(chuàng)建一個新數(shù)組,數(shù)組元素由兩個數(shù)組的元素交叉組合而成。

使用Array.reduce(),Array.map()Array.concat()來創(chuàng)建由兩個數(shù)組元素拼接而成的所有可能對并將它們存在一個數(shù)組中的數(shù)組。

?  code cat xProd.js
const xProd = (a, b) => a.reduce((acc, val) => acc.concat(b.map(v => [val, v])), []);

console.log(xProd([1, 2], ["a", "b"]));

?  code node xProd.js
[ [ 1, "a" ], [ 1, "b" ], [ 2, "a" ], [ 2, "b" ] ]

reduce初始值acc是一個空數(shù)組[],隨著遍歷的進行accconcat生成的元素組合對的數(shù)組。組合對就是由b.map(v => [val, v]生成的。也就是reduce遍歷一次時,數(shù)組a的一個元素分別和數(shù)組b的所有元素分別組成一對。

zip

Creates an array of elements, grouped based on the position in the original arrays.

Use Math.max.apply() to get the longest array in the arguments. Creates an array with that length as return value and use Array.from()with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, undefined is used where no value could be found.

const zip = (...arrays) => {
  const maxLength = Math.max(...arrays.map(x => x.length));
  return Array.from({ length: maxLength }).map((_, i) => {
    return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
  });
};

創(chuàng)建一個數(shù)組,數(shù)組元素由指定的多個數(shù)組根據(jù)位置對應(yīng)分組而成的數(shù)組構(gòu)成。例如,多個數(shù)組的第一個元素組成一個新數(shù)組,第二個元素組成一個新數(shù)組,依次類推。最終把所有分類號的數(shù)組存到一個數(shù)組中。

先使用Math.max.apply()來計算出最終成組的長度,然后使用該長度結(jié)合Array.from()map去遍歷創(chuàng)建該數(shù)組的所有分組子數(shù)組。如果其中任意一個數(shù)組在對應(yīng)位置上元素不存在(如長度為2的數(shù)組試圖獲取第3個元素)則undefined將被使用。

?  code cat zip.js
const zip = (...arrays) => {
  const maxLength = Math.max(...arrays.map(x => x.length));

  return Array.from({
    length: maxLength
  }).map((_, i) => Array.from({
      length: arrays.length
    }, (_, k) => arrays[k][i]));
};

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

?  code node zip.js
[ [ "a", 1, true ], [ "b", 2, false ] ]
[ [ "a", 1, true ], [ undefined, 2, false ] ]
const maxLength = Math.max(...arrays.map(x => x.length));

這是最終分成maxLength組,比如一個數(shù)組含有100個元素,另一個數(shù)組含有1個元素,最終要分成100組,所以需要用Math.max()去獲取所有數(shù)組中長度最長的那個。

return Array.from({
    length: maxLength
  }).map((_, i) => Array.from({
    length: arrays.length
  }).map((_, k) => arrays[k][i])
);

使用Array.from結(jié)合length生成長度為maxLength的數(shù)組這沒啥說的了,重點是map后的方法,map的每一個數(shù)組里包含多少個元素才可以呢?稍微想一下就知道,應(yīng)該是arrays的個數(shù),因為每一個數(shù)組都要拿一個出來組裝。所以這里又用了一個Array.from配上length: arrays.length來定一個數(shù)組里包含的元素數(shù)量。那么這些元素由什么組成呢?這里還是要配合一個(_, k) => arrays[k][i])方法去取arrays的元素。獲取的是對應(yīng)每一個數(shù)組的第i個元素。

zipObject

Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.

Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using Array.reduce().

const zipObject = (props, values) =>
  props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});

提供一個有效的屬性標識符的數(shù)組和一個含值數(shù)組,返回一個把屬性和值拼合的對象。即有效的屬性標識符數(shù)組的第一項為鍵,含值數(shù)組的第一項為值,依次類推。

由于一個對象值可以為undefined而鍵不能為undefined,所以只有有效的屬性標識符數(shù)組能用來決定了對象的組成結(jié)構(gòu)。因而使用Array.reduce()對該數(shù)組進行相關(guān)操作。

?  code cat zipObject.js
const zipObject = (props, values) => props.reduce((acc, val, i) => ((acc[val] = values[i]), acc), {});

console.log(zipObject(["a", "b", "c"], [1, 2]));
console.log(zipObject(["a", "b"], [1, 2, 3]));

?  code node zipObject.js
{ a: 1, b: 2, c: undefined }
{ a: 1, b: 2 }
(obj[prop] = values[index]), obj)

JavaScript的逗號運算符是指按照順序執(zhí)行表達式,最終返回最后一個表達式的運行結(jié)果。對于這個例子來說,就是先創(chuàng)造一個鍵值對,最后返回該對象。換一般的寫法就是如下:

obj[prop] = values[index];
return obj;

這點弄通了就好理解了。

實際上就是以props數(shù)組為基準,對其運用reduce方法去遍歷數(shù)組,初始值obj是一個空對象{},遍歷過程以props數(shù)組的值prop為鍵,props數(shù)組當前索引index為索引去取values數(shù)組的項為值組裝成對象并返回。

由于對象的鍵不能為undefined,因此,如果數(shù)組props的長度比數(shù)組values小,那么values多出來的那些項就不管了。如果相反,那么該對象相應(yīng)鍵的值為undefined

zipWith

Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.

Check if the last argument provided in a function. Use Math.max() to get the longest array in the arguments. Creates an array with that length as return value and use Array.from() with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, undefined is used where no value could be found. The function is invoked with the elements of each group (...group).

const zipWith = (...arrays) => {
 const length = arrays.length;
 let fn = length > 1 ? arrays[length - 1] : undefined;
 fn = typeof fn == "function" ? (arrays.pop(), fn) : undefined;
 const maxLength = Math.max(...arrays.map(x => x.length));
 const result = Array.from({ length: maxLength }).map((_, i) => {
   return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
 });
 return fn ? result.map(arr => fn(...arr)) : result;
};

創(chuàng)建一個數(shù)組,數(shù)組元素由指定的多個數(shù)組根據(jù)位置對應(yīng)分組而成的數(shù)組構(gòu)成,然后分組后的數(shù)組元素應(yīng)用指定方法進行結(jié)合。

?  code cat zipWith.js
const zipWith = (...arrays) => {
  const length = arrays.length;
  let fn = length > 1 ? arrays[length - 1] : undefined;
  fn = typeof fn === "function" ? (arrays.pop(), fn) : undefined;
  const maxLength = Math.max(...arrays.map(x => x.length));
  const result = Array.from({length: maxLength}).map((_, i) => {return Array.from({length: arrays.length}, (_, k) => arrays[k][i]);});
  return fn ? result.map(arr => fn(...arr)) : result;
};

console.log(zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c));
console.log(zipWith(
  [1, 2, 3],
  [10, 20],
  [100, 200],
  (a, b, c) => (a != null ? a : "a") + (b != null ? b : "b") + (c != null ? c : "c")
));

?  code node zipWith.js
[ 111, 222 ]
[ 111, 222, "3bc" ]
const length = arrays.length;
let fn = length > 1 ? arrays[length - 1] : undefined;
fn = typeof fn === "function" ? (arrays.pop(), fn) : undefined;

首先這里把參數(shù)長度arrays.length存到length里,然后根據(jù)參數(shù)長度length判斷參數(shù)里是否指定了某個方法。如果length小于等于1,則沒有傳入指定方法,因而fn = undefined;否則,認為參數(shù)的最后一個arrays[length - 1]傳入了方法。

接下來還得判斷fn是不是一個function,如果是,arrays.pop()把方法剔除,只留數(shù)組,然后返回fn賦值給fn;否則把undefined賦值給fn。

其實我覺得這里和前面的寫重復(fù)了,我覺得fn = typeof fn === "function" ? (arrays.pop(), fn) : undefined改成下面更好:

if (typeof fn === "function") {
  arrays.pop();
}

這樣就避免了fn的重復(fù)賦值了。因為fn = typeof fn === "function" ? (arrays.pop(), fn) : undefined這一行的作用就是為了把方法pop出去而已,沒必要再重新賦值。

const maxLength = Math.max(...arrays.map(x => x.length));

這一行計算出最終返回數(shù)組的長度,這點易證,不展開。

const result = Array.from({ length: maxLength }).map((_, i) => {
  return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
});

這里其實和前面的zip方法是一樣的,到現(xiàn)在為止返回的result是和zip的結(jié)果是一樣的。

return fn ? result.map(arr => fn(...arr)) : result;

然后判斷fn是不是非undefined,如果是不用處理直接返回result,否則對result數(shù)組所有元素調(diào)用fn方法并返回結(jié)果。需要注意的是參數(shù)…arr是需要展開的,參數(shù)不是單個的數(shù)組元素,而是數(shù)組的所有元素。

到目前為止,我已經(jīng)把數(shù)組的都過了一遍了,不過因為這個 30 seconds of code一直在開發(fā)當中,所以在我翻譯過程中,數(shù)組的項又增加了很多個,下面部分為新增的項。 all

Returns true if all elements in a collection are truthy, false otherwise.

Use Array.every(Boolean) to test if all elements in the collection are truthy.

const all = arr => arr.every(Boolean);

如果數(shù)組所有元素為真,返回true,否則返回false。

使用 Array.every(Boolean) 來檢測數(shù)組所有元素是否都為真。

?  code cat all.js
const all = arr => arr.every(Boolean);

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

?  code node all.js
true

這其實就是Array.every()函數(shù)能做的事情。參數(shù)為Boolean就是判斷是不是數(shù)組所有元素布爾為都為真。

allBy

Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.

Use Array.every() to test if all elements in the collection return true based on fn.

const allBy = (arr, fn) => arr.every(fn);

如果數(shù)組所有元素應(yīng)用了指定的斷言方法都為真,那么返回true,否則返回false。

使用Array.every()結(jié)合fn來檢測數(shù)組所有元素調(diào)用fn后布爾值是否都為真。

?  code cat allBy.js
const allBy = (arr, fn) => arr.every(fn);

console.log(allBy([4, 2, 3], x => x > 1));

?  code node allBy.js
true

all多了一個fn方法而已,只需要把every的參數(shù)換成fn就行,這沒啥可說的。

any

Returns true if at least one element in a collection is truthy, false otherwise.

Use Array.some(Boolean) to test if any elements in the collection are truthy.

const any = arr => arr.some(Boolean);

如果一個數(shù)組中至少有一個元素布爾值為真,返回true,否則返回false。

使用Array.some(Boolean)來檢測數(shù)組中是否有一個元素布爾值為真。

?  code cat any.js
const any = arr => arr.some(Boolean);

console.log(any([0, 0, 1, 0]));

?  code node any.js
true

這就是Array.some()可以做的事情,沒啥可說。

anyBy

Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise.

Use Array.some() to test if any elements in the collection return true based on fn.

const anyBy = (arr, fn) => arr.some(fn);

如果對一個數(shù)組的元素運用指定的斷言方法后至少有一個結(jié)果布爾值為真,返回true,否則返回false

使用Array.some()結(jié)合fn檢測一個數(shù)組中調(diào)用指定斷言方法后至少有一個結(jié)果布爾值為真。

?  code cat anyBy.js
const anyBy = (arr, fn) => arr.some(fn);

console.log(anyBy([0, 1, 2, 0], x => x >= 2));

?  code node anyBy.js
true

any多了一個fn方法而已,只需要把some的參數(shù)換成fn就行,這沒啥可說的。

bifurcate

Splits values into two groups. If an element in filter is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.

Use Array.reduce() and Array.push() to add elements to groups, based on filter.

const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);

把一個數(shù)組分裂成兩組。如果一個元素在filter中對應(yīng)值是truthy,那么相應(yīng)位置的被分裂元素歸屬于第一個組,否則歸屬于第二個組。

使用Array.reduce()Array.push()filter的基礎(chǔ)上把待分裂的元素添加到相應(yīng)的組中。

?  code cat bifurcate.js
const bifurcate = (arr, filter) => arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);

console.log(bifurcate(["beep", "boop", "foo", "bar"], [true, true, false, true]));

?  code node bifurcate.js
[ [ "beep", "boop", "bar" ], [ "foo" ] ]

reduce初始值acc是一個含有兩個空數(shù)組的二維數(shù)組[[], []],遍歷過程中去判斷對應(yīng)索引filter的值filter[i] 是否為truthy,若真,則把當前索引對應(yīng)元素val加到acc[0]中;否則加到acc[1]中。遍歷結(jié)束,分組完成。

bifurcateBy

Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.

Use Array.reduce() and Array.push() to add elements to groups, based on the value returned by fn for each element.

const bifurcateBy = (arr, fn) =>
  arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);

根據(jù)提供的斷言方法將一個數(shù)組分裂成兩組。如果斷言結(jié)果為truthy,該元素將被分配到第一組,否則分配在第二組。

使用Array.reduce()Array.push()在斷言方法fn的基礎(chǔ)上將待分裂的元素添加到相應(yīng)的組中。

?  code cat bifurcateBy.js
const bifurcateBy = (arr, fn) => arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);

console.log(bifurcateBy(["beep", "boop", "foo", "bar"], x => x[0] === "b"));
?  code node bifurcateBy.js
[ [ "beep", "boop", "bar" ], [ "foo" ] ]

bifurcate相比不同的地方是:

(acc[fn(val, i) ? 0 : 1].push(val), acc)

這里是對數(shù)組的元素val調(diào)用指定方法,而bifurcate是對應(yīng)位置filter[i]的直接結(jié)果。其余都是一樣的。這也很好理解了。

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

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

相關(guān)文章

  • JavaScript30, 入門放棄Array(二)

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

    pinecone 評論0 收藏0
  • JavaScript30, 入門放棄Array(五)

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

    dunizb 評論0 收藏0
  • JavaScript30, 入門放棄Array(三)

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

    FrancisSoung 評論0 收藏0
  • JavaScript30, 入門放棄Array(六)

    摘要:從數(shù)組索引為開始刪除元素,直到對數(shù)組元素運用指定方法為為止。對兩個數(shù)組的元素分別調(diào)用指定方法后,返回以運行結(jié)果為判定基準的并集,并集是原始數(shù)組元素的并集而不是運行結(jié)果的并集。 原文地址:JavaScript30秒, 從入門到放棄之Array(六)博客地址:JavaScript30秒, 從入門到放棄之Array(六) 水平有限,歡迎批評指正 tail Returns all elem...

    Freeman 評論0 收藏0
  • JavaScript30, 入門放棄

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

    TNFE 評論0 收藏0

發(fā)表評論

0條評論

閱讀需要支付1元查看
<