127个超级实用的JavaScript 代码片段,你千万要收藏好(上)

127个超级实用的JavaScript 代码片段,你千万要收藏好(上)
jiutian99
jiutian99
541
阅读
0
评论
2021年08月05日00:59:21 0 541

如果你想学习编程的话,那么,JavaScript 是你可以选择学习的,并且也是最流行的编程语言之一。正如许多人所说:“如果你只想学习一种编程语言,那就去学习 JavaScript。”

FreeCodeCamp 的创始人 Quincy Larson 在最近的一次采访中被问及开发人员应该首先学习哪种语言。他回答说:“JavaScript。”:

“软件正在吞噬世界,而 JavaScript 正在吞噬软件。JavaScript 每年都在变得越来越占主导地位,没有人知道最终会被什么取代。

如果你没有很好的理由去学习一门新语言(比如你的工作需要你维护一个非 JavaScript 代码库),我的谦虚建议是专注于在 JavaScript 方面做得更好。”

如果这对你来说,听起来很有吸引力,我在这里列出了 127 个有用的代码片段,你可以立即学习和使用它们。

因为内容比较多,我将内容分解成了上中下三部分来进行分享,今天我们先分享前面45个JavaScript代码片段,剩下的内容将在后面的两篇里进行分享。

1、all

如果谓词函数对集合中的所有元素返回 true,则此代码段返回 true,否则返回 false。 如果你想使用布尔值作为默认值,你可以省略第二个参数 fn。

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

all([4, 2, 3], x => x > 1); // true

all([1, 2, 3]); // true

2、 allEqual

此代码段检查数组的所有元素是否相等。

const allEqual = arr => arr.every(val => val === arr[0]);

allEqual([1, 2, 3, 4, 5, 6]); // false

allEqual([1, 1, 1, 1]); // true

3、approximatelyEqual

此代码段检查两个数字是否彼此近似相等,差异很小。

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;

approximatelyEqual(Math.PI / 2.0, 1.5708); // true

4、arrayToCSV

此代码段将没有逗号或双引号的元素转换为具有逗号分隔值的字符串。

const arrayToCSV = (arr, delimiter = ',') =>

  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');

arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'

arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'

5、arrayToHtmlList

此代码段将数组元素转换为<li>标签,并将它们附加到给定 ID 的列表中。

const arrayToHtmlList = (arr, listID) =>

  (el => (

    (el = document.querySelector('#' + listID)),

    (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))

  ))();

arrayToHtmlList(['item 1', 'item 2'], 'myListID');

6、attempt

此代码段执行一个函数,返回结果或捕获的错误对象。

const attempt = (fn, ...args) => {

  try {

    return fn(...args);

  } catch (e) {

    return e instanceof Error ? e : new Error(e);

  }

};

var elements = attempt(function(selector) {

  return document.querySelectorAll(selector);

}, '>_>');

if (elements instanceof Error) elements = []; // elements = []

7、average

此代码段返回两个或多个数值的平均值。

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;

average(...[1, 2, 3]); // 2

average(1, 2, 3); // 2

8、averageBy

此代码段在最初使用给定函数将每个元素映射到值后返回数组的平均值。

const averageBy = (arr, fn) =>

  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /

  arr.length;

averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5

averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5

9、bifurcate

此代码段将值分成两组,然后将过滤器的真实元素放入第一组,否则放入第二组。

你可以使用 Array.prototype.reduce() 和 Array.prototype.push() 根据过滤器将元素添加到组中。

const bifurcate = (arr, filter) =>

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

bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); 

// [ ['beep', 'boop', 'bar'], ['foo'] ]

10、bifurcateBy

此代码段根据谓词函数将值分为两组。 如果谓词函数返回一个真值,则该元素将被放置在第一组中。 否则,它将被放置在第二组中。

你可以使用 Array.prototype.reduce() 和 Array.prototype.push() 根据 fn 为每个元素返回的值将元素添加到组中。

const bifurcateBy = (arr, fn) =>

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

bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); 

// [ ['beep', 'boop', 'bar'], ['foo'] ]

11、bottomVisible

此代码段检查页面底部是否可见。

const bottomVisible = () =>

  document.documentElement.clientHeight + window.scrollY >=

  (document.documentElement.scrollHeight || document.documentElement.clientHeight);

bottomVisible(); // true

12、byteSize

此代码段以字节为单位返回字符串的长度。

const byteSize = str => new Blob([str]).size;

byteSize('?'); // 4

byteSize('Hello World'); // 11

13、capitalize

此代码段将字符串的第一个字母大写。

const capitalize = ([first, ...rest]) =>

  first.toUpperCase() + rest.join('');

capitalize('fooBar'); // 'FooBar'

capitalize('fooBar', true); // 'FooBar'

14、capitalizeEveryWord

此代码段将给定字符串中每个单词的第一个字母大写。

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

capitalizeEveryWord('hello world!'); // 'Hello World!'

15、castArray

此代码段将非数组值转换为数组。

const castArray = val => (Array.isArray(val) ? val : [val]);

castArray('foo'); // ['foo']

castArray([1]); // [1]

16、compact

此代码段从数组中删除错误值。

const compact = arr => arr.filter(Boolean);

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 

// [ 1, 2, 3, 'a', 's', 34 ]

17、countOccurrences

此代码段计算数组中某个值的出现次数。

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

18、Create Directory

此代码段用于existsSync()检查目录是否存在,mkdirSync()如果不存在则创建它。

const fs = require('fs');

const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);

createDirIfNotExists('test'); 

// creates the directory 'test', if it doesn't exist

19、currentURL

此代码段返回当前URL。

const currentURL = () => window.location.href;

currentURL(); // 'https://medium.com/@fatosmorina'

20、dayOfYear

此代码段从Date 对象中获取一年中的哪一天。

const dayOfYear = date =>

  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 272

21、decapitalize

此代码段将字符串的第一个字母转换为小写。

const decapitalize = ([first, ...rest]) =>

  first.toLowerCase() + rest.join('')

decapitalize('FooBar'); // 'fooBar'

decapitalize('FooBar'); // 'fooBar'

22、deepFlatten

此代码段递归地展平数组。

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

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

23、defaults

此代码段为对象中未定义的所有属性分配默认值。

const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);

defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }

24、defer

此代码段会延迟函数的执行,直到清除当前调用堆栈。

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);

defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'

25、degreesToRads

此代码片段可用于将值从度数转换为弧度。

const degreesToRads = deg => (deg * Math.PI) / 180.0;

degreesToRads(90.0); // ~1.5708

26、difference

此代码段查找两个数组之间的差异。

const difference = (a, b) => {

  const s = new Set(b);

  return a.filter(x => !s.has(x));

};

difference([1, 2, 3], [1, 2, 4]); // [3]

27、differenceBy

在将给定函数应用于两个列表的每个元素之后,此方法返回两个数组之间的差异。

const differenceBy = (a, b, fn) => {

  const s = new Set(b.map(fn));

  return a.filter(x => !s.has(fn(x)));

};

differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]

differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]

28、differenceWith

此代码段删除了比较器函数返回的值false。

const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); 

// [1, 1.2]

29、digitize

此代码段获取一个数字作为输入并返回其数字数组。

const digitize = n => [...`${n}`].map(i => parseInt(i));

digitize(431); // [4, 3, 1]

30、distance

此代码段通过计算距离返回两点之间的距离。

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

distance(1, 1, 2, 3); // 2.23606797749979

31、drop Elements

此代码段返回一个从左侧删除了 n 个元素的新数组。

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

drop([1, 2, 3]); // [2,3]

drop([1, 2, 3], 2); // [3]

drop([1, 2, 3], 42); // []

32、dropRight

此代码段返回一个从右侧删除了 n 个元素的新数组。

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

dropRight([1, 2, 3]); // [1,2]

dropRight([1, 2, 3], 2); // [1]

dropRight([1, 2, 3], 42); // []

33、dropRightWhile

此代码段从数组的右侧删除元素,直到传递的函数返回 true。

const dropRightWhile = (arr, func) => {

  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);

  return arr;

};

dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]

34、dropWhile

此代码段从数组中删除元素,直到传递的函数返回true。

const dropWhile = (arr, func) => {

  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);

  return arr;

};

dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]

35、elementContains

此代码段检查父元素是否包含子元素。

const elementContains = (parent, child) => parent !== child && parent.contains(child);

elementContains(document.querySelector('head'), document.querySelector('title')); // true

elementContains(document.querySelector('body'), document.querySelector('body')); // false

36、过滤重复元素

此代码段删除数组中的重复值。

const filterNonUnique = arr => [ …new Set(arr)];

filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]

37、findKey

此代码段返回满足给定函数的第一个键值。

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));

findKey(

  {

    barney: { age: 36, active: true },

    fred: { age: 40, active: false },

    pebbles: { age: 1, active: true }

  },

  o => o['active']

); // 'barney'

38、findLast

此代码段返回给定函数返回真值的最后一个元素。

const findLast = (arr, fn) => arr.filter(fn).pop();

findLast([1, 2, 3, 4], n => n % 2 === 1); // 3

39、flatten

此代码段使用递归将数组展平到指定的深度。

const flatten = (arr, depth = 1) =>

  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

flatten([1, [2], 3, 4]); // [1, 2, 3, 4]

flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]

40、forEachRight

此代码段从数组的最后一个元素开始,为数组的每个元素执行一个函数。

const forEachRight = (arr, callback) =>

  arr

    .slice(0)

    .reverse()

    .forEach(callback);

forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'

41、forOwn

此代码段迭代对象的每个属性,并分别为每个属性迭代一个回调。

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));

forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1

42、functionName

此代码段将函数的名称打印到控制台中。

const functionName = fn => (console.debug(fn.name), fn);

functionName(Math.max); // max (logged in debug channel of console)

43、从日期获取时间

此代码段可用于以Date 字符串形式从对象中获取时间。

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // "08:38:00"

44、获取日期之间的天数

此代码段可用于查找两个日期之间的天数差异。

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>

  (dateFinal - dateInitial) / (1000 * 3600 * 24);

getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2

45、getStyle

此代码段可用于获取特定元素的 CSS 规则值。

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];

getStyle(document.querySelector('p'), 'font-size'); // '16px'

总结

这是一个非常长的列表,因此,为了便于阅读与学习效率,我特意将这个列表一拆为三,今天这篇,是这个列表的上篇部分,其中,分享了45个有用的代码片段,希望对你有所帮助。

剩下两篇内容,我们将在中篇与下篇里与大家一起来学习。

今天内容先到这里了。感谢你的阅读,编程愉快!


打赏 点赞(0)
weinxin
投诉&咨询
文章名+链接地址,发送到此微信:tourism52
历史上的今天
03月
24
真正,牛逼,的,程序员,都写,C++,吗,真正,牛逼, 菜鸟教程

真正牛逼的程序员都写C++吗?

真正牛逼的程序员都写C++吗? (图片来自网络) 在程序界有一个很有意思的鄙视链,靠底层越近的开发者似乎总能睥睨更上一层的码农,然后享受智商碾压带来的舒适。 当然,以上鄙视链当段子...
SOAP,HTTP,协议,SOAPHTTP,协议,SOAP,HTTP,Binding,在,TCP, 菜鸟教程

SOAP HTTP 协议

SOAPHTTP 协议(SOAP HTTP Binding) HTTP 协议 HTTP 在 TCP/IP 之上进行通信。HTTP 客户机使用 TCP 连接到 HTTP 服务器。在建...
Web,品质,样式,表,Web,品质,样式,表,使用,对于, 菜鸟教程

Web 品质 - 样式表

Web 品质 - 样式表 使用样式表对于提升网页品质至关重要。 请勿使用 font 标签 应使用 CSS 来设置显示网页上的字体尺寸。请不要使用 font 标签。 使用 font ...
C语言的内存分配方式:堆和栈 菜鸟教程

C语言的内存分配方式:堆和栈

在 C 语言中,内存分配方式有以下三种形式: 1、从静态存储区域分配 由编译器自动分配和释放,在程序编译的时候就已经分配好内存,这块内存在程序的整个运行期间都存在,直到整个程序运行...

评论列表 共有 0 条评论

暂无评论