使用 Array.includes 来处理多重条件
// 条件语句
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}
}
如果我们想要匹配更多的红色水果呢,比方说还有很多红色水果?我们是不是得用更多的 || 来扩展这条语句?
function test(fruit) {
// 把条件提取到数组中
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries','banana'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
少写嵌套,尽早返回
让我们为之前的例子添加两个条件:
如果没有提供水果,抛出错误。
如果该水果的数量大于 10,将其打印出来。
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 条件 1:fruit 必须有值
if (fruit) {
// 条件 2:必须为红色
if (redFruits.includes(fruit)) {
console.log('red');
// 条件 3:必须是大量存在
if (quantity > 10) {
console.log('big quantity');
}
}
} else {
throw new Error('No fruit!');
}
}
// 测试结果
test(null); // 报错:No fruits
test('apple'); // 打印:red
test('apple', 20); // 打印:red,big quantity
让我们来仔细看看上面的代码,我们有:
1 个 if/else 语句来筛选无效的条件
3 层 if 语句嵌套(条件 1,2 & 3)
就我个人而言,我遵循的一个总的规则是当发现无效条件时尽早返回。
/_ 当发现无效条件时尽早返回 _/
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!'); // 条件 1:尽早抛出错误
if (!redFruits.includes(fruit)) return; // 条件 2:当 fruit 不是红色的时候,直接返回
console.log('red');
// 条件 3:必须是大量存在
if (quantity > 10) {
console.log('big quantity');
}
}
使用函数默认参数和解构
function test(fruit, quantity) {
if (!fruit) return;
const q = quantity || 1; // 如果没有提供 quantity,默认为 1
console.log(`We have ${q} ${fruit}!`);
}
//测试结果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!
事实上,我们可以通过函数的默认参数来去掉变量 q
function test(fruit, quantity = 1) { // 如果没有提供 quantity,默认为 1
if (!fruit) return;
console.log(`We have ${quantity} ${fruit}!`);
}
//测试结果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!
相较于 switch,Map / Object 也许是更好的选择
让我们看下面的例子,我们想要根据颜色打印出各种水果:
function test(color) {
// 使用 switch case 来找到对应颜色的水果
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
//测试结果
test(null); // []
test('yellow'); // ['banana', 'pineapple']
同样的结果可以通过使用 Map 来实现同样的效果:
// 使用 Map 来找到对应颜色的水果
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);
function test(color) {
return fruitColor.get(color) || [];
}
使用 Array.every 和 Array.some 来处理全部/部分满足条件
JavaScript 数组函数来减少代码行数。观察以下的代码,我们想要检查是否所有的水果都是红色的:
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
}
通过 Array.every 来缩减代码:
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
}
备注自己看:(数组遍历 for、forEach 、map、filter、reduce、every、some)
要检查是否有至少一个水果是红色的,我们可以使用 Array.some 仅用一行代码就实现出来。
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
}
向一个对象数组里面添加新的属性
var arry= [{a:11,b:22,c:33,d:44},{a:11,b:0,c:0,d:44},{a:11,b:22,c:99,d:99}];
var arry2=[];
arry.map(((item, index)=> {
arry2.push(Object.assign({},item,{mess1:item.c,mess2:item.d}))
}))
console.log(arry2);
将一个对象数组数据拿出来变成另一个对象
var arry= [{a:11,b:22,c:33,d:44},{a:11,b:0,c:0,d:44},{a:11,b:22,c:99,d:99}];
var arry2=[];
arry.map(((item, index)=> {
arry2.push(Object.assign({},{mess1:item.c,mess2:item.d}))
}))
console.log(arry2);