如何让编写的js代码更短?下面本篇文章就来给大家分享4个编写短小精炼js代码的小技巧,希望对大家有所帮助!

Javascript 里的逻辑运算符与(&&)可以产生短路,例如
console.log(true && 0 && 2); // 0 console.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麻烦
例如
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代码的小技巧(分享)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号