# 你试过不用if撸代码吗？

2018.09.15 14:50 4769浏览

### 示例1: 统计数组中的奇数

``````const arrayOfIntegers = [1, 4, 5, 9, 0, -1, 5];
``````

#### 使用if

``````let counter = 0;
arrayOfIntegers.forEach((integer) => {
const remainder = Math.abs(integer % 2);
if (remainder === 1) {
counter++;
}
});

console.log(counter);
``````

#### 不用if

``````let counter = 0;

arrayOfIntegers.forEach((integer) => {
const remainder = Math.abs(integer % 2);
counter += remainder;
});

console.log(counter);
``````

### 示例2： 判断工作日和周末

#### 使用if

``````const weekendOrWeekday = (inputDate) => {
const day = inputDate.getDay();

if (day === 0 || day === 6) {
return 'weekend';
}

return 'weekday';

// Or, for ternary fans:
// return (day === 0 || day === 6) ? 'weekend' : 'weekday';
};

console.log(weekendOrWeekday(new Date()));
``````

#### 不用if

``````const weekendOrWeekday = (inputDate) => {
const day = inputDate.getDay();

return weekendOrWeekday.labels[day] ||
weekendOrWeekday.labels['default'];
};

weekendOrWeekday.labels = {
0: 'weekend',
6: 'weekend',
default: 'weekday'
};

console.log(weekendOrWeekday(new Date()));
``````

### 示例3: doubler函数

• 如果参数是数字，则乘以2(i.e. `5 => 10`, `-10 => -20`)；
• 如果参数是字符串，则每个字符重复2次 (i.e. `'hello' => 'hheelloo'`)；
• 如果参数是函数，则调用2次；
• 如果参数是数组，则将每一个元素作为参数，调用doubler函数
• 如果参数是对象，则将每个属性值作为参数，调用doubler函数

#### 使用switch

``````const doubler = (input) => {
switch (typeof input) {
case 'number':
return input + input;
case 'string':
return input
.split('')
.map((letter) => letter + letter)
.join('');
case 'object':
Object.keys(input)
.map((key) => (input[key] = doubler(input[key])));
return input;
case 'function':
input();
input();
}
};

console.log(doubler(-10));
console.log(doubler('hey'));
console.log(doubler([5, 'hello']));
console.log(doubler({ a: 5, b: 'hello' }));
console.log(
doubler(function() {
console.log('call-me');
}),
);
``````

#### 不用switch

``````const doubler = (input) => {
return doubler.operationsByType[typeof input](input);
};

doubler.operationsByType = {
number: (input) => input + input,
string: (input) =>
input
.split('')
.map((letter) => letter + letter)
.join(''),
function: (input) => {
input();
input();
},
object: (input) => {
Object.keys(input)
.map((key) => (input[key] = doubler(input[key])));
return input;
},
};

console.log(doubler(-10));
console.log(doubler('hey'));
console.log(doubler([5, 'hello']));
console.log(doubler({ a: 5, b: 'hello' }));
console.log(
doubler(function() {
console.log('call-me');
}),
);
``````

9人点赞

• 9
• 2
• 收藏
• 共同学习，写下你的评论

0/150