20 个超级有用的 JavaScript 技巧,让你的工作更轻松(下)
上一篇 /
下一篇 2022-11-08 13:34:47
11. 条件查找简化
如果我们想根据不同的类型调用不同的方法,我们可以使用多个 else if 语句或开关,但是还有比这更好的简化技巧吗?其实和之前的switch简化是一样的。
// bad
if (type === "test1") {
test1();
} else if (type === "test2") {
test2();
} else if (type === "test3") {
test3();
} else if (type === "test4") {
test4();
} else {
throw new Error("Invalid value " + type);
}
// better
var types = {
test1,
test2,
test3,
test4,
};
types[type] && types[type]();
12. 对象属性赋值
let test1 = "a";
let test2 = "b";
// bad
let obj = { test1: test1, test2: test2 };
// better
let obj = { test1, test2 };
13. 解构赋值
// bad
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
// better
const { test1, test2, test3 } = this.data;
14. 模板字符串
如果你厌倦了使用 + 将多个变量连接成一个字符串,这个简化技巧会让你头疼。
// bad
const welcome = "Hi " + test1 + " " + test2 + ".";
// better
const welcome = `Hi ${test1} ${test2}`;
15. 跨越字符串
// bad
const data =
"hello maxwell this is a test\n\t" + "test test,test test test test\n\t";
// better
const data = `hello maxwell this is a test
test test,test test test test`;
16. indexOf的按位化简
在数组中查找某个值时,我们可以使用 indexOf() 方法。但是还有更好的方法,我们来看这个例子。
// bad
if (arr.indexOf(item) > -1) {
// item found
}
if (arr.indexOf(item) === -1) {
// item not found
}
// better
if (~arr.indexOf(item)) {
// item found
}
if (!~arr.indexOf(item)) {
// item not found
}
//The bitwise (~) operator will return true (except for -1),
//the reverse operation only requires !~. Alternatively, the includes() function can be used.
if (arr.includes(item)) {
// true if the item found
}
17. 将字符串转换为数字
有诸如 parseInt 和 parseFloat 等内置方法可用于将字符串转换为数字。我们也可以简单地通过在字符串前面提供一元运算符 (+) 来做到这一点。
// bad
let total = parseInt("583");
let average = parseFloat("32.5");
// better
let total = +"583";
let average = +"32.5";
18. 按顺序执行 Promise
如果你有一堆异步或普通函数都返回要求你一个一个执行它们的Promise怎么办?
async function getData() {
const promises = [fetch("url1"), fetch("url2"), fetch("url3"), fetch("url4")];
for (const item of promises) {
// Print out the promise
console.log(item);
}
// better
for await (const item of promises) {
// Print out the results of the request
console.log(item);
}
}
等待所有Promiae完成。
Promise.allSettled() 方法接受一组 Promise 实例作为参数,包装到一个新的 Promise 实例中。在所有这些参数实例都返回结果(已完成或已拒绝)之前,包装器实例不会结束。
有时候,我们并不关心异步请求的结果,我们只关心是否所有请求都结束了。这时候,Promise.allSettled() 方法就非常有用了。
const promises = [fetch("index.html"), fetch("https://does-not-exist/")];
const results = await Promise.allSettled(promises);
// Filter out successful requests
const successfulPromises = results.filter((p) => p.status === "fulfilled");
// Filter out failed requests and output the reason
const errors = results
.filter((p) => p.status === "rejected")
.map((p) => p.reason);
19.交换数组元素的位置
// bad
const swapWay = (arr, i, j) => {
const newArr = [...arr];
let temp = newArr[i];
newArr[i] = list[j];
newArr[j] = temp;
return newArr;
};
//Since ES6, swapping values from different locations in an array has become much easier
// better
const swapWay = (arr, i, j) => {
const newArr = [...arr];
const [newArr[j],newArr[i]] = [newArr[i],newArr[j]];
return newArr;
};
20. 带范围的随机数生成器
有时你需要生成随机数,但又希望数字在一定范围内,则可以使用此工具。
function randomNumber(max = 1, min = 0) {
if (min >= max) {
return max;
}
return Math.floor(Math.random() * (max - min) + min);
}
生成随机颜色
function getRandomColor() {
const colorAngle = Math.floor(Math.random() * 360);
return `hsla(${colorAngle},100%,50%,1)`;
}
到这里,我要跟你分享的20 个 JavaScript 的小技巧就结束了,希望这些小技巧对你有用。
收藏
举报
TAG:
软件开发
Java