1.英文字符串首字母大写
Javascript没有内置的首字母大写函数,因此我们可以使用以下代码。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
// Result: Follow for more
2.数组去重
可以使用 JavaScript 中的Set
轻松删除重复项
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
3.从 URL 获取查询参数
可以通过传递 window.location
或原始 URL goole.com?search=easy&page=3
轻松地从 url 检索查询参数
const getParameters = (URL) => {
URL = JSON.parse(
'{"' +
decodeURI(URL.split("?")[1])
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
return JSON.stringify(URL);
};
getParameters(window.location);
// Result: { search : "easy", page : 3 }
4.校验数字是奇数还是偶数
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: True
5.求数字的平均值
使用reduce
方法找到多个数字之间的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
6.回到顶部
可以使用 window.scrollTo(0, 0)
方法自动滚动到顶部。将 x
和 y
都设置为 0。
const goToTop = () => window.scrollTo(0, 0);
goToTop();
7.翻转字符串
可以使用 split
、reverse
和 join
方法轻松反转字符串。
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
8.校验数组是否为空
一行代码检查数组是否为空,将返回true
或false
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
9.获取用户选择的文本
使用内置的getSelection
属性获取用户选择的文本。
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
打乱数组
可以使用sort
和 random
方法打乱数组
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]