- 多重判断中使用Array.includes
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
复制代码
- 少嵌套,早返回(发现无效的条件时,及早return)
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');
}
}
复制代码
- 使用默认参数和解构
function test(fruit, quantity = 1) {
if (!fruit) return;
console.log(`We have ${quantity} ${fruit}!`);
}
复制代码
- 倾向对象遍历而不是switch语句
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
复制代码
- 对 全部/部分判断 使用Array.every/Array.some
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
const isAllRed = fruits.every(f => f.color == 'red');
复制代码
作者:call_me_R