1. maxItemOfArray

If anyone asks me what programming language they should learn as a beginner, I’ll tell them it’s JavaScript. This powerful language gets involved in almost every aspect of programming — frontend, backend, web app, desktop app, mobile app. The list goes on.

如果有人问我作为初学者应该学习哪种编程语言,我会告诉他们是JavaScript。 这种强大的语言几乎参与了编程的各个方面-前端,后端,Web应用程序,桌面应用程序,移动应用程序。 清单继续。

In today’s story, I’ll show you 18 useful JavaScript snippets that I use most of the time. They helped me save time for common development tasks. Let’s get into it.

在今天的故事中,我将向您展示我大部分时间使用的18个有用JavaScript代码段。 他们帮助我节省了执行常见开发任务的时间。 让我们开始吧。

1. maxItemOfArray (1. maxItemOfArray)

This one return the maximum number from an array.

这个返回一个数组的最大数目。

const maxItemOfArray = (arr) => […arr].sort((a, b) => b — a).slice(0, 1)[0];let maxItem = maxItemOfArray([3, 5, 12, 5]);

2. areAll等于 (2. areAllEqual)

This snippet checks if all the items of a array are equal.

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

const areAllEqual = array => array.every(item => item === array[0]);let check1 = areAllEqual([3, 5, 2]); // false
let check2 = allEqual([3, 3, 3]); // true

3. averageOf (3. averageOf)

This one returns the average number of the given numbers.

这将返回给定数字的平均数。

const averageOf = (…numbers) => numbers.reduce((a, b) => a + b, 0) / numbers.length;let average = averageOf(5, 2, 4, 7); // 4.5

4. reverseString (4. reverseString)

This snippet reverses a string.

此代码段将字符串反转。

const reverseString = str => […str].reverse().join(‘’);let a = reverseString(‘Have a nice day!’); // !yad ecin a evaH

5. sumOf (5. sumOf)

This one returns the sum of the given numbers.

这将返回给定数字的总和。

const sumOf = (…numbers) => numbers.reduce((a, b) => a + b, 0);let sum = sumOf(5, -3, 2, 1); // 5

6. findAndReplace (6. findAndReplace)

This snippets find a given word in a string and replace with another one.

这些片段在字符串中找到给定的单词,并替换为另一个。

const findAndReplace = (string, wordToFind, wordToReplace) => string.split(wordToFind).join(wordToReplace);let result = findAndReplace(‘I like banana’, ‘banana’, ‘apple’); // I like apple

7. RGBToHex (7. RGBToHex)

This one convert a color in RGB mode to Hex.

此选项将RGB模式下的颜色转换为十六进制。

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, ‘0’);let hex = RGBToHex(255, 255, 255); // ffffff

8.洗牌 (8. shuffle)

Do you want to know how any music player can shuffle playing item? This snippet will show you how.

您是否想知道任何音乐播放器如何随机播放播放项目? 此代码段将向您展示如何。

const shuffle = ([…array]) => {
let m = array.length;

while (m) {
const i = Math.floor(Math.random() * m--);
[array[m], array[i]] = [array[i], array[m]];
} return array;
};shuffle([5, 4, 3, 6, 20]);

9. removeFalseValues (9. removeFalseValues)

This snippet removes false values from an array, which include false, undefined, NaN, empty.

此代码段从数组中删除错误的值,其中包括false,undefined,NaN,empty。

const removeFalseValues = arr => arr.filter(item => item);let arr = removeFalseValues([3, 4, false, ‘’, 5, true, undefined, NaN, ‘’]); // [3, 4, 5, true]

10. removeDuplicatedValues (10. removeDuplicatedValues)

This one removes duplicated item from an array.

这将从数组中删除重复的项目。

const removeDuplicatedValues = array => […new Set(array)];let arr = removeDuplicatedValues([5, 3, 2, 5, 6, 1, 1, 6]); // [5, 3, 2, 6, 1]

11. getTimeFromDate (11. getTimeFromDate)

This snippet returns time in string from a Date object.

该代码段以日期对象的字符串形式返回时间。

const getTimeFromDate = date => date.toTimeString().slice(0, 8);let time = getTimeFromDate(new Date()); // 09:46:08

12.大写AllWords (12. capitalizeAllWords)

This one capitalizes the first letter of all words in a string.

这将大写字符串中所有单词的第一个字母。

const capitalizeAllWords = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());let str = capitalizeAllWords(‘i love reading book’); // I Love Reading Book

13. getDayDiff (13. getDayDiff)

This one returns the difference in days between two dates.

该值返回两个日期之间的天数差。

const getDayDiff = (date1, date2) => (date2 — date1) / (1000 * 3600 * 24);let diff = getDayDiff(new Date(‘2020–04–01’), new Date(‘2020–08–15’)); // 136

14. radianToDegree (14. radianToDegree)

This one convert an angle from radian to degree.

这将弧度从弧度转换为度。

const radianToDegree = radian => (radian * 180.0) / Math.PI;let degree = radianToDegree(2.3); // 131.78

15. isValidJSON (15. isValidJSON)

This snippet checks if a given string is a valid JSON.

此代码段检查给定的字符串是否为有效的JSON。

const isValidJSON = string => {
try {
JSON.parse(string);
return true;
} catch (error) {
return false;
}
};let check1 = isValidJSON(‘{“title”: “javascript”, “price”: 14}’); // true
let check2 = isValidJSON(‘{“title”: “javascript”, “price”: 14, subtitle}’); // false

16. toWords (16. toWords)

This one is used to convert a given string into an array of words.

这个用于将给定的字符串转换为单词数组。

const toWords = (string, pattern = /[^a-zA-Z-]+/) => string.split(pattern).filter(item => item);let words = toWords(‘I want to be come a great programmer’); // [“I”, “want”, “to”, “be”, “come”, “a”, “great”, “programmer”]

17. scrollToTop (17. scrollToTop)

If you’re at the bottom of a long page and you want to scroll up to the top quickly, this snippet can help you in a smoothly way.

如果您位于长页面的底部,并且想要快速向上滚动至顶部,则此代码段可以帮助您顺利进行。

const scrollToTop = () => {
const t = document.documentElement.scrollTop || document.body.scrollTop; if (t > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, t — t / 8);
}
};

18. isValidNumber (18. isValidNumber)

This one is used to validate if a number is valid.

这个用来验证数字是否有效。

const isValidNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) === n;let check1 = isValidNumber(10); // true
let check2 = isValidNumber(‘a’); // false

That’s it. However, it’s not all. If you have your own list of useful snippets, let me know in the comment below and I will add them to the story. It would be wonderful if this story becomes an ultimate list of useful JavaSnippets.

而已。 但是,还不是全部。 如果您有自己的有用代码清单,请在下面的评论中告诉我,我将它们添加到故事中。 如果这个故事成为有用的JavaSnippets的最终清单,那将是很棒的。

进一步阅读 (Further Reading)

翻译自: https://medium.com/javascript-in-plain-english/18-useful-javascript-snippets-for-common-tasks-you-can-use-from-today-96fa03ce3df6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值