JavaScript30秒, 从入门到放弃

发布时间:2019-08-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了JavaScript30秒, 从入门到放弃脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

意思

最近很火的gIThub上的库30-seconds-of-code,特别有意思,代码也很优雅。

  1. 能学es6
  2. 自己翻译,能学英语
  3. 代码很美,很优雅,美即正义
  4. 函数式表达,享受

arrayGcd

Calculates the greatest common denominator (gcd) of an array of numbers.

Use Array.reduce() and the gcd formula (uses recursion) to calculate the greatest common denominator of an array of numbers.

const arrayGcd = arr =>{
  const gcd = (x, y) => !y ? x : gcd(y, x % y);
  return arr.reduce((a,b) => gcd(a,b));
}
// arrayGcd([1,2,3,4,5]) -> 1
// arrayGcd([4,8,12]) -> 4

计算数组最大公约数

使用Array.reduce()gcd公式(使用递归)来计算一个数组的最大公约数

➜  code cat arrayGcd.js
const arrayGcd = arr => {
    const gcd = (x, y) => !y ? x : gcd(y, x % y);
    return arr.reduce((a, b) => gcd(a, b));
}

console.log(arrayGcd([1, 2, 3, 4, 5]));
console.log(arrayGcd([4, 8, 12]));
➜  code node arrayGcd.js
1
4

gcd即欧几里德算法,具体不表,自查。这里用到了数组的reduce方法,相当简洁,reduce不太了解的话,看下mdn就明白。

arrayLcm

Calculates the lowest common multiple (lcm) of an array of numbers.

Use Array.reduce() and the lcm formula (uses recursion) to calculate the lowest common multiple of an array of numbers.

const arrayLcm = arr =>{
 const gcd = (x, y) => !y ? x : gcd(y, x % y);
 const lcm = (x, y) => (x*y)/gcd(x, y) 
 return arr.reduce((a,b) => lcm(a,b));
}
// arrayLcm([1,2,3,4,5]) -> 60
// arrayLcm([4,8,12]) -> 24

计算一个数组的最小公倍数。

使用Array.reduce()lcm公式(使用递归)来计算一个数组的最大公约数。

➜  code cat arrayLcm.js
const arrayLcm = arr => {
  const gcd = (x, y) => (!y ? x : gcd(y, x % y));
  const lcm = (x, y) => x * y / gcd(x, y);
  return arr.reduce((a, b) => lcm(a, b));
};

console.log(arrayLcm([1, 2, 3, 4, 5]));
console.log(arrayLcm([4, 8, 12]));
➜  code node arrayLcm.js
60
24

lcm算法用到了前面的gcd算法,关键点是两个数的最大公约数和最小公倍数的乘积正好就是这两个数的乘积。

arrayMax

Returns the maximum value in an array.

Use Math.max() combined with the sPRead operator (...) to get the maximum value in the array.

const arrayMax = arr => Math.max(...arr);
// arrayMax([10, 1, 5]) -> 10

返回数组中最大的值。

使用Math.max()ES6扩展运算符返回数组中最大的值。

➜  code cat arrayMax.js
const arrayMax = arr => Math.max(...arr);

console.log(arrayMax([10, 1, 5]));
➜  code node arrayMax.js
10

实际上就是Math.max()干的事,没啥可说的了。

arrayMin

Returns the minimum value in an array.

Use Math.min() combined with the spread oPErator (...) to get the minimum value in the array.

const arrayMin = arr => Math.min(...arr);
// arrayMin([10, 1, 5]) -> 1

返回数组中最小的值。

使用Math.min()ES6的扩展运算返回数组中最小的值。

➜  code cat arrayMin.js
const arrayMin = arr => Math.min(...arr);

console.log(arrayMin([10, 1, 5]));
➜  code node arrayMin.js
1

实际上就是Math.min()干的事,没啥可说的了。

chunk

Chunks an array into smaller arrays of a specified size.

Use Array.From() to create a new array, that fits the number of chunks that will be produced. Use Array.slice() to map each element of the new array to a chunk the length of size. If the original array can't be split evenly, the final chunk will contain the remaining elements.

const chunk = (arr, size) =>
 Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]

按照给定的size将一个数组切分成含有size个数的更小数组块的数组。

使用Array.from()生产新的符合定义的数组。使用Array.slice()来截取指定size个元素组成新的数组块。如果原数组长度不能被size整除,最后的剩余的那些元素将归属于最后一个块。

➜  code cat chunk.js
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

console.log(chunk([1, 2, 3, 4, 5], 2));
➜  code node chunk.js
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

Array.from(arrayLike, mapFn, thisarg)这个方法呢,第一个参数是一个类数组或者可迭代的对象,第二个参数是一个应用在每一个数组元素上的方法,第三个参数就是改变this的指向了。通俗说就是指定谁是你的爸爸。

这里用了一个{ length: Math.ceil(arr.length / size) }迭代对象,length指定了迭代次数,即按照size分块后的数组长度,正好就是原数组长度除以size向上取整的值。向上取整就是为了满足不能完全整除的情况。比如5个元素按照2个一组进行分块,分了两组两个元素的,剩最后一个元素成了独立组,总长为3。

(v, i),由于迭代的时候数组在每一个位置上都是以undefined初始化的,所以v一直都是undefined

arr.slice(i * size, i * size + size)迭代过程中每次截取size个数的元素组成新数组。这里的i就是随着迭代变化,比如length是3,i就是0,1,2。

这里的迭代类似python里的range

➜  code python
Python 3.6.4 (default, Dec 23 2017, 10:37:40)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> arr = [1,2,3,4,5]
>>> size = 2
>>> for i in range(math.ceil(len(arr) / size)):
...     print('index: ', i)
...
index:  0
index:  1
index:  2

compact

Removes falsey values from an array.

Use Array.filter() to filter out falsey values (false, null, 0, "", undefined, and NaN).

const compact = arr => arr.filter(Boolean);
// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]

移除掉数组里falsey的元素。(这个falsey不太好翻译,不是错误的意思,而是该值布尔运算值为false的意思,我个人常用!!进行判断)。

使用Array.filter()falsenull0""undefinedNaN这些falsey过滤掉。

➜  code cat compact.js
const compact = arr => arr.filter(Boolean);

console.log(compact([0, 1, false, 2, "", 3, "a", "e" * 23, NaN, "s", 34]));
➜  code node compact.js
[ 1, 2, 3, 'a', 's', 34 ]

Array.prototype.filter()干的,没啥好说。

countOccurrences

Counts the occurrences of a value in an array.

Use Array.reduce() to increment a counter each time you encounter the specific value inside the array.

const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3

统计一个元素在一个数组中出现的次数。

使用Array.reduce()在遍历过程中如果指定元素在数组中出现,则增加它的次数值,默认次数为0。

➜  code cat countOccurrences.js
const countOccurrences = (arr, value) =>
  arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);

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

三元运算符(v === value ? a + 1 : a + 0)遍历过程中判断遍历数组v是否严格等于指定值value,是,次数a+1;否,a+0

最后的一个逗号后面的0,是这个初始值,即a=0,这个懂reduce方法都知道,特别指出是,因为这个函数一定会有返回值,如果指定元素没有在数组中出现一次,返回值是0,所以必须得初始化为0

deepFlatten

Deep flattens an array.

Use recursion. Use Array.concat() with an empty array ([]) and the spread operator (...) to flatten an array. Recursively flatten each element that is an array.

const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]

深度摊平一个数组。

使用递归方法。结合Array.concat()、空数组[]ES6的扩展运算符来摊平一个数组,如果摊平的元素还是一个数组,就再递归运用该方法。

➜  code cat deepFlatten.js
const deepFlatten = arr =>
  [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

console.log(deepFlatten([1, [2], [[3], 4], 5]));
➜  code node deepFlatten.js
[ 1, 2, 3, 4, 5 ]

三元运算符(Array.isArray(v) ? deepFlatten(v) : v)判断v是否是一个数组,是,返回递归运用deepFlatten(v)后的值;否,直接返回v

[].concat(...arr.map(fn))用空数组把map运算产生的数组进行扩展运算值拼接成结果数组返回。

该方法是深度摊平方法,在很多时候还有特定的摊平一层的需求,underscore就有。实现的方法就是再加一个标志参数进行处理即可。具体不讲了。

应该会写一个系列,今天先写到这,明天继续。

个人翻译水平有限,欢迎大家在issues上批评指正。JavaScript30秒, 从入门到放弃
博客地址:JavaScript30秒, 从入门到放弃
微信公众号地址:JavaScript30秒, 从入门到放弃

脚本宝典总结

以上是脚本宝典为你收集整理的JavaScript30秒, 从入门到放弃全部内容,希望文章能够帮你解决JavaScript30秒, 从入门到放弃所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。