文章用于扩宽思维倒是不错,工作中还是该写 if 就 if,既然有为何不用,逻辑简单清晰明了。
统计数组中的奇数
假设我们有一个整数数组arrayNum,现在需要统计其中奇数的个数:
const arrayNum = [1, 4, 5, 9, 0, -1, 5];
function getOddCount1(arrayNum){
//with if
let count = 0;
arrayNum.forEach((num) => {
let value = Math.abs(num % 2);
if (value === 1) {
count++;
}
});
return count;
}
function getOddCount2(arrayNum){
//without if
let count = 0;
arrayNum.forEach((num) => {
let value = Math.abs(num % 2);
count += value;
});
return count;
}
getOddCount1(arrayNum);
getOddCount2(arrayNum);
判断工作日和周末
给定一个日期(比如new Date()),判断它是工作日还是周末,分别返回”weekend”和”weekday”。
const getWeekendOrWeekday1 = (inputDate) => {
//with if
const day = inputDate.getDay();
if (day === 0 || day === 6) {
return 'weekend';
}
return 'weekday';
// Or, for ternary fans:
// return (day === 0 || day === 6) ? 'weekend' : 'weekday';
};
const getWeekendOrWeekday2 = (inputDate) => {
//without if
const day = inputDate.getDay();
switch (day) {
case 0:
return 'weekend';
case 6:
return 'weekend';
default:
return 'weekday';
}
};
const getWeekendOrWeekday3 = (inputDate) => {
//without if
let labels = {
0: 'weekend',
6: 'weekend',
default: 'weekday'
};
//without if
const day = inputDate.getDay();
return labels[day] || labels['default'];
};
var date = new Date();
getWeekendOrWeekday1(date);
getWeekendOrWeekday2(date);
getWeekendOrWeekday3(date);
发表评论