![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cGcq5SN1UjN2gDZiFjM1AjYhNzMzYzXxQTMwATM4IzLclDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.jpg)
英文 | https://betterprogramming.pub/127-helpful-javascript-snippets-you-can-learn-in-30-seconds-or-less-part-1-of-6-bc2bc890dfe5
翻譯 | 楊小二
接上前面一期的内容《127個超級實用的JavaScript 代碼片段,你千萬要收藏好(中)》
86、negate
此代碼段可用于将 not 運算符 ( !) 應用于帶有參數的謂詞函數。
const negate = func => (...args) => !func(...args);
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
87、 nodeListToArray
此代碼段可用于将 nodeList 轉換為數組。
const nodeListToArray = nodeList => [...nodeList];
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
88、pad
如果字元串短于指定長度,則此代碼段可用于在字元串的兩側填充指定字元。
const pad = (str, length, char = ' ') =>
str.padStart((str.length + length) / 2, char).padEnd(length, char);
pad('cat', 8); // ' cat '
pad(String(42), 6, '0'); // '004200'
pad('foobar', 3); // 'foobar'
89、 radsToDegrees
此代碼段可用于将角度從弧度轉換為度數。
const radsToDegrees = rad => (rad * 180.0) / Math.PI;
radsToDegrees(Math.PI / 2); // 90
90、随機生成十六進制顔色代碼
此代碼段可用于生成随機的十六進制顔色代碼。
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
randomHexColorCode(); // "#e34155"
91、 randomIntArrayInRange
此代碼段可用于生成具有n指定範圍内的随機整數的數組。
const randomIntArrayInRange = (min, max, n = 1) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
92、randomIntegerInRange
此代碼段可用于生成指定範圍内的随機整數。
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(0, 5); // 3
93、RandomNumberInRange
此代碼段可用于傳回指定範圍内的随機數。
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
randomNumberInRange(2, 10); // 6.0211363285087005
94、ReadFileLines
此代碼段可用于通過從檔案中擷取行數組來讀取檔案。
const fs = require('fs');
const readFileLines = filename =>
fs
.readFileSync(filename)
.toString('UTF8')
.split('\n');
let arr = readFileLines('test.txt');
console.log(arr); // ['line1', 'line2', 'line3']
95、 重定向到一個 URL
此代碼段可用于重定向到指定的 URL。
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
redirect('https://google.com');
96、反轉字元串
此代碼段可用于反轉字元串。
const reverseString = str => [...str].reverse().join('');
reverseString('foobar'); // 'raboof'
97、round
此代碼段可用于将數字四舍五入到指定的位數。
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01
98、runPromisesInSeries
此代碼段可用于連續運作一系列 Promise。
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
const delay = d => new Promise(r => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]);
// Executes each promise sequentially, taking a total of 3 seconds to complete
99、sample
此代碼段可用于從數組中擷取随機數。
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
sample([3, 7, 9, 11]); // 9
100、sampleSize
此代碼段可用于從數組中的唯一位置擷取 n 個随機元素,直至數組的大小。 使用 Fisher-Yates 算法對數組中的元素進行混洗。
const sampleSize = ([...arr], n = 1) => {
let m = arr.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr.slice(0, n);
};
sampleSize([1, 2, 3], 2); // [3,1]
sampleSize([1, 2, 3], 4); // [2,3,1]
101、scrollToTop
此代碼段可用于平滑滾動到目前頁面的頂部。
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
scrollToTop();
102、serializeCookie
此代碼段可用于将 cookie 名稱-值對序列化為 Set-Cookie 标頭字元串。
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
serializeCookie('foo', 'bar'); // 'foo=bar'
103、setStyle
此代碼段可用于為特定元素設定 CSS 規則的值。
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
setStyle(document.querySelector('p'), 'font-size', '20px');
// The first <p> element on the page will have a font-size of 20px
104、shallowClone
此代碼段可用于建立對象的淺層克隆。
const shallowClone = obj => Object.assign({}, obj);
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b
105、Show
此代碼段可用于顯示指定的所有元素。
const show = (...el) => [...el].forEach(e => (e.style.display = ''));
show(...document.querySelectorAll('img')); // Shows all <img> elements on the page
106、shuffle
此代碼段可用于使用Fisher-Yates 算法随機排序數組的元素。
const shuffle = ([...arr]) => {
let m = arr.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr;
};
const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]
107、similarity
此代碼段可用于傳回出現在兩個數組中的元素數組。
const similarity = (arr, values) => arr.filter(v => values.includes(v));
similarity([1, 2, 3], [1, 2, 4]); // [1, 2]
108、sleep
此代碼段可用于通過将異步函數置于睡眠狀态來延遲其執行。
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function sleepyWork() {
console.log("I'm going to sleep for 1 second.");
await sleep(1000);
console.log('I woke up after 1 second.');
}
109、smoothScroll
此代碼段可用于将調用它的元素平滑地滾動到浏覽器視窗的可見區域。
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar
110、 sortCharactersInString
此代碼段可用于按字母順序對字元串中的字元進行排序。
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
sortCharactersInString('cabbage'); // 'aabbceg'
111、splitLines
此代碼段可用于将多行字元串拆分為行數組。
const splitLines = str => str.split(/\r?\n/);
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
112、stripHTMLTags
此代碼段可用于從字元串中删除 HTML/XML 标記。
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
113、sum
此代碼段可用于查找兩個或多個數字或數組的總和。
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10
114、tail
此代碼段可用于擷取包含數組中除第一個元素之外的所有元素的數組。如果數組隻有一個元素,那麼将傳回具有該元素的數組。
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
tail([1, 2, 3]); // [2,3]
tail([1]); // [1]
115、take
此代碼段可用于擷取從開頭删除 n 個元素的數組。
const take = (arr, n = 1) => arr.slice(0, n);
take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3], 0); // []
116、takeRight
此代碼段可用于擷取n 從末尾删除元素的數組。
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
takeRight([1, 2, 3], 2); // [ 2, 3 ]
takeRight([1, 2, 3]); // [3]
117、timeTaken
此代碼段可用于找出執行函數所需的時間。
const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
118、times
此代碼段可用于疊代回調n 時間。
const times = (n, fn, context = undefined) => {
let i = 0;
while (fn.call(context, i) !== false && ++i < n) {}
};
var output = '';
times(5, i => (output += i));
console.log(output); // 01234
119、 toCurrency
此代碼段可用于格式化數字(如貨币)。
const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
toCurrency(123456.789, 'EUR'); // €123,456.79 | currency: Euro | currencyLangFormat: Local
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States)
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ $ | currency: US Dollar | currencyLangFormat: Farsi
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local
toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish
120、 toDecimalMark
此代碼段使用toLocaleString() 函數将浮點運算轉換為小數點形式,方法是使用數字生成逗号分隔的字元串。
const toDecimalMark = num => num.toLocaleString('en-US');
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
121、toggleClass
此代碼段可用于切換元素的類。
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
122、tomorrow
此代碼段可用于擷取明天日期的字元串表示。
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return t.toISOString().split('T')[0];
};
tomorrow(); // 2019-09-08 (if current date is 2018-09-08)
123、unfold
此代碼段可用于使用疊代器函數和初始種子值建構數組。
const unfold = (fn, seed) => {
let result = [],
val = [null, seed];
while ((val = fn(val[1]))) result.push(val[0]);
return result;
};
var f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]
124、union
此代碼段可用于查找兩個數組的并集,進而生成一個包含來自兩個數組但不重複的元素的數組。
const union = (a, b) => Array.from(new Set([...a, ...b]));
union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
125、uniqueElements
這段代碼使用 ES6 Set 和 ...rest 運算符來隻擷取每個元素一次。
const uniqueElements = arr => [...new Set(arr)];
uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
126、validateNumber
此代碼段可用于檢查值是否為數字。
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
validateNumber('10'); // true
127、words
此代碼段将字元串轉換為單詞數組。
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
總結
這個非常長的清單,到這裡,就全部分享完畢了,希望你在學習它的時候,也可以立即開始實用它。