短路javascript 里的逻辑运算符与(&&)可以产生短路,例如
console.log(true && 0 && 2); // 0console.log(true && 'test' && 2) // 2
即代码从左往右,如果遇到undefined,null,0等等会被转化为false的值时就不再继续运行。
x == 0 && foo()// 等价于if( x == 0 ){ foo()}
链判断运算符 '?'假设有一个对象
const student = { name : { firstname : 'joe' }}
我们希望firstname存在的情况下做一些事情, 我们不得不一层一层检查
if(student && student.name && student.name.firstname){ console.log('student first name exists')}
采用链判断运算符会在某一层取不到值的时候停止并返回undefined
if(student?.name?.firstname){ console.log('student first name exists')}
空值合并运算符 ''我们有时候会使用三元运算来简化if...else... 或者返回一个默认值
const foo = () => { return student.name?.firstname ? student.name.firstname : 'firstname do not exist'}console.log(foo())
这种情况,我们可以通过空值合并进一步简化代码
const foo = () => { return student.name?.firstname 'firstname do not exist'}console.log(foo())
很像或||运算符,但只对undefined 和 null起作用,可以避免值是0麻烦
尽量避免if else 嵌套例如
const foo = () => { if(x<1) { return 'x is less than 1' } else { if(x > 1){ return 'x is greater than 1' } else { return 'x is equal to 1' } }}
通过删除 else 条件可以使 if else 嵌套变得不那么复杂,因为 return 语句将停止代码执行并返回函数
const foo = () => { if(x<1){ return 'less than 1' } if(x>1){ return 'x is greater than 1' } return 'x is equal to 1'}
好的代码不一定要追求尽可能的短,有时候过于精简的代码会使debug的过程更加麻烦,所以可读性才是最重要的,特别是在多人协作的情况下。
更多编程相关知识,请访问:编程入门!!
以上就是4个编写短小精炼js代码的小技巧(分享)的详细内容。