当前位置: 移动技术网 > IT编程>网页制作>CSS > 5个技巧写更好的JavaScript条件语句

5个技巧写更好的JavaScript条件语句

2018年12月26日  | 移动技术网IT编程  | 我要评论

5个技巧写更好的javascript条件语句

1、对于多个条件使用array.includes方法

下面来看一个例子。

// 条件

function test(fruit) {

if (fruit == 'apple' || fruit == 'strawberry') {

console.log('red');

}

}

咋眼一看,这段代码没什么问题。但是试想一下,如果我们的判断条件不止上面两个呢,比如fruit可能值还有cherry(樱桃)等等,那么这时候我们怎么做呢?难道还是要更多的||吗?

让我们通过array.includes()重写上面的例子。

function test(fruit) {

// 提取值到数组

const redfruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

if (redfruits.includes(fruit)) {

console.log('red');

}

}

我们把上面的if判断的值,提取到了数组,然后通过array.includes方法来判断,这样做,代码看起来更加简洁。

2、少嵌套,尽早返回

接下来让我们来扩展上面的例子:

如果没有fruit提供,就抛出错误提示 如果fruit的数量大于10,就打印fruit

function test(fruit, quantity) {

const redfruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

// condition 1: fruit must has value

if (fruit) {

// condition 2: must be red

if (redfruits.includes(fruit)) {

console.log('red');

// condition 3: must be big quantity

if (quantity > 10) {

console.log('big quantity');

}

}

} else {

throw new error('no fruit!');

}

}

// test results

test(null); // error: no fruits

test('apple'); // print: red

test('apple', 20); // print: red, big quantity

上面例子我们可以看到,达到了三层循环。这是时候,我们可以当发现值无效时,尽早就提供返回。

function test(fruit, quantity) {

const redfruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

// condition 1: throw error early

if (!fruit) throw new error('no fruit!');

// condition 2: must be red

if (redfruits.includes(fruit)) {

console.log('red');

// condition 3: must be big quantity

if (quantity > 10) {

console.log('big quantity');

}

}

}

这样做了过后,我们会发现少了嵌套。这样的代码有个好处(想象当你的第一个if代码特别多的时候,else就会在很底部的位置,意思就是你需要滚动才能看到)。

3、使用默认的函数参数和解构

我们来看一段很熟悉的代码:

function test(fruit, quantity) {

if (!fruit) return;

const q = quantity || 1; // if quantity not provided, default to one

console.log(`we have ${q} ${fruit}!`);

}

//test results

test('banana'); // we have 1 banana!

test('apple', 2); // we have 2 apple!

我们经常使用上面的语句来检测null/undefined值,然后来设置一个默认值,这在以前的做法是很明智的,但是其实我们可以通过es6的新特性,设置函数参数的默认值。

function test(fruit, quantity = 1) { // if quantity not provided, default to one

if (!fruit) return;

console.log(`we have ${quantity} ${fruit}!`);

}

//test results

test('banana'); // we have 1 banana!

test('apple', 2); // we have 2 apple!

这样对于上面的代码,如果参数quantity没有传递值,那么就会使用默认值。这样做是不是更加的简单直接呢?

如果我们的fruit是一个对象呢,可以赋值默认参数吗?

function test(fruit) {

// printing fruit name if value provided

if (fruit && fruit.name) {

console.log (fruit.name);

} else {

console.log('unknown');

}

}

//test results

test(undefined); // unknown

test({ }); // unknown

test({ name: 'apple', color: 'red' }); // apple

看看上面的例子,如果变量name属性存在,我们就打印出来,否则就打印'unkown'。对于上面的fruit&fruit.name检测,我们可以通过对象属性的解构来实现。

function test({name} = {}) {

console.log (name || 'unknown');

}

//test results

test(undefined); // unknown

test({ }); // unknown

test({ name: 'apple', color: 'red' }); // apple

我们只需要fruit中的name属性值,那么就可以使用上面的方法,然后name就当做变量在函数中直接使用,替代了上面的fruitt.name,更加方便直接。

4、选择map/object,而不是switch语句

让我们来看看下面的例子:

function test(color) {

// use switch case to find fruits in color

switch (color) {

case 'red':

return ['apple', 'strawberry'];

case 'yellow':

return ['banana', 'pineapple'];

case 'purple':

return ['grape', 'plum'];

default:

return [];

}

}

//test results

test(null); // []

test('yellow'); // ['banana', 'pineapple']

上面的例子看起来似乎没有任何问题,但是有没有发现代码特别的繁琐。我们可以使用对象字面量来达到相同的目的。

// use object literal to find fruits in color

const fruitcolor = {

red: ['apple', 'strawberry'],

yellow: ['banana', 'pineapple'],

purple: ['grape', 'plum']

};

function test(color) {

return fruitcolor[color] || [];

}

或者,你可以使用map来取得相同的结果。

// use map to find fruits in color

const fruitcolor = new map()

.set('red', ['apple', 'strawberry'])

.set('yellow', ['banana', 'pineapple'])

.set('purple', ['grape', 'plum']);

function test(color) {

return fruitcolor.get(color) || [];

}

map和对象的主要区别就是(也就是map出现的意义)可以做到值和值得对应。

object 结构提供了“字符串—值”的对应,map 结构提供了“值—值”的对应,是一种更完善的 hash 结构实现。如果你需要“键值对”的数据结构,map 比 object 更合适。

那这样的话,我们是不是应该禁止使用switch语句呢?答案是否定的,方法没有好坏,取决于你要使用的场景。

对于上面的例子,我们还可以使用filter来取得相同的结果。

const fruits = [

{ name: 'apple', color: 'red' },

{ name: 'strawberry', color: 'red' },

{ name: 'banana', color: 'yellow' },

{ name: 'pineapple', color: 'yellow' },

{ name: 'grape', color: 'purple' },

{ name: 'plum', color: 'purple' }

];

function test(color) {

// use array filter to find fruits in color

return fruits.filter(f => f.color == color);

}

同样的结果,我们使用了4种方法,只能说一句code is funny!

5 、对于所有或者部分的条件判断使用array.every & array.some

看看下面的例子,我们想检测是否所有fruit都是红颜色:

const fruits = [

{ name: 'apple', color: 'red' },

{ name: 'banana', color: 'yellow' },

{ name: 'grape', color: 'purple' }

];

function test() {

let isallred = true;

// condition: all fruits must be red

for (let f of fruits) {

if (!isallred) break;

isallred = (f.color == 'red');

}

console.log(isallred); // false

}

上面的代码一看,好长。那么有没有办法来缩短上面的代码取得相同的结果呢。往下看array.every

const fruits = [

{ name: 'apple', color: 'red' },

{ name: 'banana', color: 'yellow' },

{ name: 'grape', color: 'purple' }

];

function test() {

// condition: short way, all fruits must be red

const isallred = fruits.every(f => f.color == 'red');

console.log(isallred); // false

}

every顾名思义,就是检测所有,只有当每一个值都返回true的时候,最终结果才返回true。还有一点值得说明的就是,every同条件语句判断一样,是惰性的,什么意思呢,因为every是所有的值返回true才最最终结果为true,所以只要执行到一个值返回为false,就不会往下执行了(直接返回false)。相当于条件判断的&。

如果我们想检测是否有一个fruit的颜色为红色呢?array.some

const fruits = [

{ name: 'apple', color: 'red' },

{ name: 'banana', color: 'yellow' },

{ name: 'grape', color: 'purple' }

];

function test() {

// condition: if any fruit is red

const isanyred = fruits.some(f => f.color == 'red');

console.log(isanyred); // true

}

代码很简洁,目的也达到了。同样,some也是惰性的,和条件判断的||很相似。因为some是只要一个返回true,那么最终结果就为true,所以当执行一个代码,得到的结果为true的时候,就不会再往下执行了。

对于数组的方法,array.map、array.foreach,还有上面提到的array.filter,以及一些归并方法reduce、reduceright。数组迭代+归并,这些方法在实际的代码中,都能提高很大的效率,写出更好的代码。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网