# 在 JavaScript 中的 if 語句中指定多個條件

Sahil Bhosale 2023年10月12日

``````var arr = [5, 25, 70, 62, 20, 89];

arr.forEach(num => {
if (num == 20) {
// do something
}
})
``````

## 在 JavaScript 中使用邏輯運算子的 `if` 語句中新增乘法條件

• 和 （`&&`

AND 運算子的真值表：

`A` `B` `A && B`
`True` `True` `True`
`True` `False` `False`
`False` `True` `False`
`False` `False` `False`

``````var arr = [5, 25, 70, 62, 20, 89];

arr.forEach(num => {
if (num == 20 && num % 2 == 0) {
console.log(num);
}
})
``````

``````20
``````

• 或 (`||`)

OR 運算子的真值表：

| `A` | `B` | `A || B` |
| ——- | ——- | :—–: |
| `True` | `True` | `True` |
| `True` | `False` | `True` |
| `False` | `True` | `True` |
| `False` | `False`| `False` |

``````var arr = [5, 25, 70, 62, 20, 89];

arr.forEach(num => {
if (num == 20 || num % 2 == 0) {
console.log(num);
}
})
``````

``````70
62
20
``````

## 在 JavaScript 的 `if` 語句中組合使用 AND 和 OR 運算子

``````var arr = [5, 25, 70, 62, 20, 89];

arr.forEach(num => {
if ((num != 20 && num % 2 == 0) || (num > 50) && (num < 100)) {
console.log(num);
}
})
``````

``````70
62
89
``````

``````var arr = [5, 25, 70, 62, 20, 89];

arr.forEach(num => {
if ((num > 50) && (num < 100)) {
console.log('The number is in the range of 20 to 100.');
} else if (num != 20 && num % 2 == 0) {
console.log('The number 20 is divisible by 2.')
} else if ((num < 50) || (num == 5)) {
console.log('The number is less than 50.')
}
})
``````

``````The number is less than 50.
The number is less than 50.
The number is in the range of 20 to 100.
The number is in the range of 20 to 100.
The number is less than 50.
The number is in the range of 20 to 100.
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.