你现在需要知道的 Javascript 代码片段🔥 - #3
嗨,朋友们!
希望你们都过得好。
欢迎回到我的系列文章,我每周都会分享 10 个 JS 代码片段,总共超过 50 个必备的 JS 代码片段。
如果您错过了,这里是上一期。
1️⃣ 平均值
此代码片段返回两个或多个数值的平均值。
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
2️⃣ 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
3️⃣ capitalizeEveryWord
此代码片段将给定字符串中每个单词的首字母大写。
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!'
4️⃣ 创建目录
此代码片段使用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
5️⃣ 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]
6️⃣ 差异
此代码片段查找两个数组之间的差异。
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
difference([1, 2, 3], [1, 2, 4]); // [3]
7️⃣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 } ]
8️⃣ 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]
9️⃣ 数字化
此代码片段获取一个数字作为输入并返回其数字数组。
const digitize = n => [...`${n}`].map(i => parseInt(i));
digitize(431); // [4, 3, 1]
🔟 距离
此代码片段通过计算欧几里得距离返回两点之间的距离。
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
distance(1, 1, 2, 3); // 2.23606797749979
感谢您的阅读。希望本文对您有所帮助。
订阅我的新闻通讯,即可持续关注此类文章以及众多科技新闻和产品发布。
下次再见,
Abhiraj