7 个实用的 JavaScript 技巧
7 个实用的 JavaScript 技巧
不用多说,让我们深入探讨一下:
- 过滤虚假值:
如果你有一个值数组,你可以null
undefined
0
""
NaN
false
使用以下方法过滤掉虚假值(Boolean()
//Example 1
const x = ["a","",3,false,"hello",undefined]
const y = x.filter(Boolean);
console.log(y) // ["a",3,"hello"]
//Use it like this
myArray.filter(Boolean);
2. 对小数取整而不是Math.floor()
在您想要显示整数时很有用
(编辑:这会删除小数,因此它实际上就像Math.ceil()
对负数一样,感谢@ veljko94pesic)
//Example 1
const x = 1.5
const y = ~~x
console.log(y) // Equals 1
//Example 2
const a = -1.5
const b = ~~a
console.log(b) // Equals -1
//Example 3
const z = ~~2.73123
console.log(z) // Equals 2
3. 隐式布尔强制
将值更改为布尔值(而不是Boolean(value)
)
const x = {}
const y = !!x //Equals true
console.log(y) // true
4. 数组中的最后一个项目
您可以使用带有负索引的 Array.slice() 来向后计数。
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8]
console.log(array.slice(-1)); // Equals [8]
console.log(array.slice(-2)); // Equals [7, 8]
console.log(array.slice(-3)); // Equals [6, 7, 8]
5. 使用隐式数字强制转换+
+
在任何值前面加上 a都会尝试将其更改为数字,类似于Number(value)
。这也可以用于 Date 对象,作为Date.getTime()
//Example 1
const x = new Date()
const y = +x
console.log(y) //Equals 1591887393586 (gives back time in ms)
对于执行此操作很有用(10 秒后获取时间)
const z = new Date(+new Date() + 10 *1000)
console.log(z) //Equals 1591887403586
6.方法参数验证,
如果输入未给出,则抛出错误
const isRequired = () => { throw new Error('param is required'); };
const print = (value = isRequired()) => {
console.log(`${value}`)
};
print(2);// Equals 2
print()// Throws error
print(null)// Equals null
7. 吞掉所有承诺的错误
通常情况下,Promise.all()
如果数组中任何一个 Promise 被拒绝,就会抛出错误。我们可以对每个 Promise 使用 map 和 catch 来忽略错误。
const promiseArray = [
Promise.reject(null),
Promise.resolve(100),
Promise.resolve("More data"),
Promise.reject(new Error('Throw an error here'))
];
//Map and catch for promises
//And just console.log them
const all = await Promise.all(
promiseArray.map(p => p.catch(console.log))
)
就这些!
你还有什么 JavaScript 技巧吗?
欢迎在下方评论区留言 🙂