条件语句
1、if……else……
2、 if……else if……
3、switch……case……
文章来源于https://scotch.io/bar-talk/5-tips-to-write-better-conditionals-in-javascript
文章目录
1. 对多个条件使用Array.includes
// condition
function test(char) {
if (char == 'a' || fruit == 'b') {
console.log('true');
}
}
当出现多个“||”时,那该如何?
function test(char) {
// extract conditions to array
const chars = ['a', 'b', 'c', 'd'];
if (chars.includes(char)) {
console.log('true');
}
}
2. 少嵌套,早返回
function test(char,num) {
const chars = ['a', 'b', 'c', 'd'];
// condition 1: char must has value
if(char){
// condition 2: must be true
if (chars.includes(char)) {
console.log('true');
// condition 3: must be not zero
if(num>0){
console.log('not zero');
}
}
}else {
throw new Error('no char!');
}
}
// test results
test(null); // error: no char!
test('a'); // print: true
test('a', 20); // print: true, no char!
修改为
function test(char,num) {
const chars = ['a', 'b', 'c', 'd'];
// condition 1: char must has value
if(!char)throw new Error('no char!');
// condition 2: must be true
if (chars.includes(char)) {
console.log('true');
// condition 3: must be not zero
if(num>0){
console.log('not zero');
}
}
}
更进一步
function test(char,num) {
const chars = ['a', 'b', 'c', 'd'];
// condition 1: char must has value
if(!char)throw new Error('no char!');
// condition 2: must be true
if (!chars.includes(char)) return;
console.log('true');
// condition 3: must be not zero
if(num>0){
console.log('not zero');
}
}
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!
改为:
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!
如果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
改为
// destructing - get name property only
// assign default empty object {}
function test({
name} = {
}) {
console.log (name || 'unknown');
}
//test results
test(undefined); // unknown
test({
}); // unknown
test({
name: 'apple', color: 'red' }); // apple
4. 支持Map / Object Literal而不是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] || [];
}
或者
// 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) || [];
}
Using Array.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);
}
5. 对所有/部分条件使用Array.every和Array.some
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
}
改为
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
}
或者
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
}