基于 es6 的 javascript 实用方法

一、求数字数组的平均数 - 使用 数组的 reduce() 方法将每个值添加到累加器,初始值为0,总和除以数组长度。

const average = arr => arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / arr.length;

// average([1,2,3]) -> 2

二、Anagrams of string(字符串的排列组合,结果没去重,有重复项)

const anagrams = str => {

 

  if(str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];

 

  return str.split('').reduce((accumulator, currentValue, currentIndex) =>

    //这里要用箭头函数,由于箭头函数不绑定this, 它会捕获其所在(即定义的位置)上下文的this值, 作为自己的this值,这里的 this 指的是 []

    accumulator.concat(anagrams(str.slice(0, currentIndex) + str.slice(currentIndex + 1)).map(val => currentValue + val)), []);

};

// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']

三、大写每个单词的首字母 - 字符串的 replace() 方法匹配每个单词的第一个字符,并使用字符串的 toUpperCase() 方法将其大写。

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

// capitalizeEveryWord('hello world!') -> 'Hello World!'

四、字符串首字母大写 - 其余部分默认不变,第二个参数传入 true,则将除首字母的其余部分转为小写

const capitalize = (str, lowerRest = false) =>

  str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));

// capitalize('myName') -> 'MyName'

// capitalize('myName', true) -> 'Myname'

五、字符串检查回文(指顺读和倒读都一样的词语) - 首先把字符串转为小写同时使用正则去除非字母的字符(\W 等价于 “[^A-Za-z0-9_]” ,在这里 [\W_] 指的是  “[^A-Za-z0-9]” 不包括下划线的字符集合),再和反转过来的字符串做比较,是回文则返回true。

const palindrome = str => {

  const s = str.toLowerCase().replace(/[\W_]/g, '');

  return s === s.split('').reverse().join('');

}

// palindrome('tac9 cat') -> true

六、计数数组中值的出现次数 - 每次遇到数组中的指定值时,使用数组的 reduce() 来递增计数器。

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

七、当前URL - 使用window.location.href来获取当前URL。

const currentUrl = () => window.location.href;
// currentUrl() -> 'https://google.com'

八、Curry 函数 - 如果提供的参数(args)数量足够,则调用传递函数fn,否则返回一个 curried 函数。

const curry = (fn, arity = fn.length, ...args) =>

  arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);

// curry(Math.pow)(2)(10) -> 1024

注: 在es5里,函数的arguments只是array-like object, 直到 ES6 终于对 arguments 提供了一个替代品 - rest parameters(rest 运算符):

function foo (...args) {

  // 这里 args 终于是真正的 Array 了!

}

九、Deep flatten array - 使用递归,把多元数组转为一元数组,使用数组的 reduce() 方法和递归来获取所有不是数组的元素,并扁平化每个是数组的元素。

const deepFlatten = arr =>

  arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);

// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]

十、数组之间的区别 - 从b创建一个Set进行去重,然后在a上使用Array.filter(),返回一个只保留b中不包含值的数组。

const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };

// difference([1,2,3], [1,2]) -> [3]

十一、两点之间的距离 - 计算一直角三角形的斜边长度, 使用Math.hypot() 返回多个数的平方和的平方根,计算两点之间的欧几里德距离。

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);

// distance(1,1,2,3) -> 2.23606797749979c

十二、是否可以整除 - 使用模运算符(%)来检查余数是否等于0。

const isDivisible = (dividend, divisor) => dividend % divisor === 0;

// isDivisible(6,3) -> true

十三、转义字符串的特殊字符 - 使用字符串的 replace() 方法来转义特殊字符。

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

// escapeRegExp('(test)') -> \(test\)

十四、判断是偶数或奇数 - 取余后如果是0则是偶数返回true,否则返回false。

const isEven = num => num % 2 === 0;

// isEven(3) -> false

十五、阶乘 - 使用递归。如果n小于或等于1,则返回1。否则返回n和n - 1的阶乘的乘积。

const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720

十六、斐波那契数组生成器 - 创建一个特定长度的空数组,初始化前两个值(0和1)。使用 Array.reduce() 向数组中添加值,后面的一个数等于前面两个数相加之和(前两个除外)。

const fibonacci = n =>

  Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);

// fibonacci(5) -> [0,1,1,2,3]

 十七、过滤掉数组中的非唯一值 - 在 Array.filter() 函数中,分别从前和后查找某一个item,如果不同则至少有两个,不返回这个值。

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]

十八、Flatten 扁平化二维数组 - 使用 reduce() 来获取数组中的所有元素,并使用 concat() 合并数组中的每一个值或者数组。

const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
// flatten([1,[2],3,4]) -> [1,2,3,4]

十九、从数字数组中获取最大值 - 使用Math.max()与 扩展运算符(...)结合得到数组中的最大值。...arr可以获得数组中的一维的值,类似于 10,1,5

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

二十、获取当前的滚动位置 - 如果是window,使用pageXOffset和pageYOffset,如果是元素使用scrollLeft和scrollTop,可以传递参数el定义滚动的Dom容器,默认window。

const getScrollPos = (el = window) =>
({
x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop
});
// getScrollPos() -> {x: 0, y: 100}

二十一、求两个数字的最大公约数 - 使用递归。 基本情况是当y(x对y取余的值)等于0时,返回x即为最大公约数。 否则, 继续执行gcd函数(传参为返回上一次 x%y 的值和 本次 x%y 的值)。

const gcd = (x, y) => !y ? x : gcd(y, x % y);
// gcd (20, 8) -> 4

posted @ 2018-03-27 14:07  heroljy  阅读(292)  评论(0编辑  收藏  举报