java 判断语句 性能_前端性能优化:js中优化条件判断语句

在开发过程中,由于追求开发速度,我们往往很多时候都没有注意代码的可读性与性能,这里介绍几个技巧,让你写出可读性强、简洁的js代码

1、多个条件满足之一时,推荐使用Array.includes// 优化前

function test(val) {

if (val === 'js' || val === 'java' || val === 'python') {

console.log('编程语言')

}

}

// 优化后

function test(val) {

cosnt arr = ['js', 'java', 'python']

if (arr.includes(val)) {

console.log('编程语言')

}

}

2、减少嵌套,尽早返回// 优化前

function test(val) {

if (val) {

if (val === 'js') {

console.log(val)

} else {

console.log('其他')

}

} else {

return

}

}

// 优化后

function test(val) {

if (!val) return

val === 'js' ? console.log(val) : console.log('其他')

}

3、使用函数的默认参数与解构// 优化前

function test(val, num) {

const item = num || 1

console.log(`this is ${item}${val}`)

}

test('js', 4)

// 优化后

function test(val, num = 1) {

console.log(`this is ${num}${val}`)

}

test('java', 4)

如果默认参数是对象呢?我们就可以使用解构了// 优化前

function test(val) {

if (val && val.name) {

console.log(val.name)

} else {

console.log('null')

}

}

test({name: 'js', num: 1})

// 优化后

function test({name} = {}) {

console.log(name)

}

test({name: 'js', num: 1})

4、使用map或者对象字面量替代switch语句// 优化前

function test(num) {

switch(num) {

case 1:

return ['js', 'java']

case 2:

return ['python', 'ruby']

case 3:

return ['php', 'c#']

default

}

conosle.log(num)

}

test(1)

// 优化后,对象字面量方式

function test(num) {

const arr = {

1: ['js', 'java'],

2: ['python', 'ruby'],

3: ['php', 'c#'],

}

console.log(arr[num])

}

test(1)

// map方式

function test(num) {

const arr = new Map()

.set(1, ['js', 'java'])

.set(2, ['python', 'ruby'])

.set(3, ['php', 'c#'])

console.log(arr.get(num))

}

test(1)

5、使用Array.every()或者Array.some()// 优化前

const item = [

{name: 'js', num: 2},

{name: 'java', num: 4},

{name: 'pyton', num: 2},

{name: 'php', num: 1},

]

function test() {

let isNumTwo = true

for (let val of item) {

if (!isNumTwo) break

isNumTwo = (val.num === 2)

}

console.log(isNumTwo) // false

}

test()

// 优化后

const item = [

{name: 'js', num: 2},

{name: 'java', num: 4},

{name: 'pyton', num: 2},

{name: 'php', num: 1},

]

function test() {

const isNumTwo = item.some(val => val.num === 2)

console.log(isNumTwo) // true

}

test()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值