1.使用 Array.includes 来处理多重条件(判断是否包含某一元素,返回true或false; indexOf返回-1或元素位置,但是indexOf无法判断是否有NaN的元素)
function test(color) {
// 把条件提取到数组中
const colors = ['red', 'white', 'black', 'green'];
if(colors.includes(color)) {
console.log(color);
}
}
例如上面的例子,我们只用调用includes,即可判断,而不用去使用for循环遍历;
2.少写嵌套,尽早返回
原则就是: 发现了无效的条件,我们就尽早返回,避免层级嵌套过多;
3. 使用函数默认参数和解构;
例如下面的例子,我们可以不用在去判断是否传递了count这个值,或者我们想要在没有传递count的时候,赋予一个默认的值
function test(color, count = 1) { // 如果没有提供 count,默认为 1
if(!color) return;
console.log(`color is ${count}${color}!`);
}
//测试结果
test('red'); // color is 1 red
test('black', 0); // color is 0 black
我们看到count我们在函数参数里面给赋值了,记住哦,所有的函数参数都可以有默认值;我们这里同样可以为color赋值;
相信大家对下面的说法应该很熟悉
// 如果有值,则打印出来
function test(colors) {
// 如果有值,则打印出来
if(colors && colors.name) {
console.log(colors.name);
} else {
console.log('nocolor');
}
}
我之前就一直是这样子写,但是通过默认参数和解构赋值的方法来避免写出 fruit && fruit.name 这种条件。
// 默认参数为空对象 {}
function test({name} = {}) {
console.log(name || 'unknown');
}
既然我们只需要 colors的 name 属性,我们可以使用 {name}
来将其解构出来,之后我们就可以在代码中使用 name 变量来取代 colors.name。
这里我们还使用{}作为其默认值;是因为传递一个undefinde的值的话会报错哦;
4.相比 switch,或许Map / Object 是更好的选择
function test(color) {
// 使用 switch case 来找到对应颜色的水果
switch(color) {
case 'red':
return ['blood', 'bloodman'];
case 'yellow':
return ['dark', 'darkmask'];
case 'purple':
return ['dress', 'dresswhite'];
default:
return [];
}
}
这里我们使用了switch来做处理,根据传递的值进行处理;但是我们或许可以使用对象或者map来处理更方便
// 使用对象字面量来找到对应颜色的水果
const manyColor = {
red: ['blood', 'bloodman'],
yellow: ['dark', 'darkmask'],
purple: ['dark', 'darkmask']
};
function test(color) {
return mangColor[color] || [];
}
// 使用 Map 来找到对应颜色的水果
const manyColor = newMap()
.set('red', ['blood', 'bloodman'])
.set('yellow', ['dark', 'darkmask'])
.set('purple', ['dark', 'darkmask']);
function test(color) {
return manyColor.get(color) || [];
}
5.使用 Array.every 和 Array.some 来处理全部/部分满足条件
every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)
- 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
- 如果所有元素都满足条件,则返回 true。
-
every() 不会对空数组进行检测。
注意: every() 不会改变原始数组。
-
array.every(function(currentValue,index,arr), thisValue)
-
currentValue 必须。当前元素的值 index 可选。当前元素的索引值 arr 可选。当前元素属于的数组对象
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined" |
array.some(function(currentValue,index,arr),thisValue)
some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。
some() 方法会依次执行数组的每个元素:
- 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
- 如果没有满足条件的元素,则返回false。
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组。
currentValue | 必须。当前元素的值 |
index | 可选。当前元素的索引值 |
arr | 可选。当前元素属于的数组对象 |
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined" |