忍者般的 JavaScript 技巧
1)如果存在
2) 末尾带零的小数
3) 函数返回
4)价差操作商
5)必填参数
6) '+':整数类型转换
7) '~':按位索引
开发者你好,
今天我将分享我最喜欢的 7 个 JavaScript 简写技巧,它们会让你的代码看起来既酷炫又简洁。
好了,我们开始吧。
1)如果存在
在介绍这种简写方式之前,让我先解释一下 Javascript 的假值。
假值是指计算结果为 FALSE 的值,例如在检查变量时。JavaScript 中只有六个假值:undefined、null、NaN、0、""(空字符串)以及 false。
除了这六个之外,所有值在 JavaScript 中都被视为真值。
在进行“if 检查”时,有时可以省略赋值运算符。
速记表达
if (myValue) // myValue can be any truthy value
等效的完整手写表达式将是
长手表达
if (Boolean(myValue))
2) 末尾带零的小数
const maxValue = 100000
与其这样写数字,我们可以用一种更酷的方式来写,去掉末尾的零。
const maxValue = 1e5 // 100000
1e0 === 1
1e1 === 10
1e2 === 100
1e3 === 1000
1e4 === 10000
1e5 === 100000
3) 函数返回
在所有 JavaScript 函数中,默认返回值都是 undefined。要从函数中返回一个值,我们需要使用 return 关键字。但是,在箭头函数中,单个语句会隐式地返回其执行结果(为了省略 return 关键字,函数必须省略花括号 ({}))。
// longhand
const add = (a, b) => {
return a + b
}
// shorthand
const add = (a, b) => (a + b)
4)价差操作商
当然,说到简写技巧,就不得不提扩展运算符。它是 ES6 的语法,更加简洁易用。它可以用来替代某些数组函数。扩展运算符其实就是三个点。
const a = [1, 2, 3]
/* To concat a with b*/
// longhand
const b = [4, 5, 6].concat(a)
// shorthand
const b = [4, 5, 6, ...a]
const c = [4, ...a, 5, 6] // You can use it anywhere inside an array
/* You can even use a spread operator to clone an array */
const copyOfA = [...a] // Traditional way is the use of slice method
5)必填参数
由于 JavaScript 变量是弱类型化的,我们无法验证函数中的必需参数。默认情况下,如果函数参数没有作为实参传递,JavaScript 会将其视为 undefined。要验证参数是否必需,你需要使用 if 语句,或者可以像下面这样进行默认赋值。
// longhand
function foo(bar) {
if(bar === undefined) {
throw new Error('Missing parameter!!!');
}
return bar;
}
// shorthand
required = () => {
throw new Error('Missing parameter!!!');
}
foo = (bar = required()) => {
return bar;
}
6) '+':整数类型转换
在所有这些方法中,我最常用的是这个。我们经常会重载“+”运算符来进行字符串连接。我发现“+”运算符另一个最有用的用途是进行整数类型转换。
// longhand
const num1 = parseInt("100")
const num2 = parseFloat("100.01")
// shorthand
const num1 = +"100" // converts to int data type
const num2 = +"100.01" // converts to float data type
7) '~':按位索引
这里另一个常用的技巧是将“~”运算符与 `indexOf` 函数结合使用。`~`(按位取反)运算符的作用是取一个数字的所有位并取反。`indexOf`方法
会返回元素在数组或字符串中首次出现的索引。由于 0 在 JavaScript 中是假值,我们不能直接在 `if` 语句中使用 ` indexOf`方法。因此,对于 0,`~` 运算符会返回 -1;对于 -1,它会返回 0。
// longhand
if(arr.indexOf(item) > -1) { // Confirm item IS found
}
if(arr.indexOf(item) === -1) { // Confirm item IS NOT found
}
// shorthand
if(~arr.indexOf(item)) { // Confirm item IS found
}
if(!~arr.indexOf(item)) { // Confirm item IS NOT found
}
感谢大家的阅读!别忘了在评论区分享你最喜欢的速记表达方式哦!
祝您编程愉快!:)
文章来源:https://dev.to/deepanmania/javascript-in-a-ninja-way-1mhf