1、使用Array.includes处理多种条件
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}}
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
2、减少嵌套,尽早return
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (fruit) {
if (redFruits.includes(fruit)) {
console.log('red');
if (quantity > 10) {
console.log('big quantity');
}
}
} else {
throw new Error('No fruit!');
}
}
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'];
if (!fruit) throw new Error('No fruit!');
if (redFruits.includes(fruit)) {
console.log('red');
if (quantity > 10) {
console.log('big quantity');
}
}
}
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!');
if (!redFruits.includes(fruit)) return;
console.log('red');
if (quantity > 10) {
console.log('big quantity');
}
}
3、使用函数默认参数和解构
function test(fruit, quantity) {
if (!fruit) return;
const q = quantity || 1;
console.log(`We have ${q} ${fruit}!`);
}
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!
function test(fruit, quantity = 1) {
if (!fruit) return;
console.log(`We have ${quantity} ${fruit}!`);
}
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!
function test(fruit) {
if (fruit && fruit.name) {
console.log (fruit.name);
} else {
console.log('unknown');
}
}
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
function test({name} = {}) {
console.log (name || 'unknown');
}
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
// 在执行test(undefined)这行代码时就会报错:无法解析’undefined’或’null’的属性name,因为undefined没有name这个属性
function test(fruit) {
console.log(__.get(fruit, 'name', 'unknown');
}
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
4、对所有或部分规则使用Array.every和Array.some
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
function test() {
let isAllRed = true;
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() {
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() {
const isAnyRed = fruits.some(f => f.color == 'red');
console.log(isAnyRed); // true
}