Array.includes
一個最常見的循環例子:
function demo(fruit) {
if(fruit === 'apple' || fruit === 'strawberry'){
console.log('red fruit')
}
}
這是一段沒有任何問題的,內部含有條件判斷的函數,然而如果我們有很多種類的水果需要匹配更多的水果顏色,這時我們如果還按照傳統的條件判斷,就需要寫更多的 ||
來擴展我們條件語句。
我們可以使用 Array.includes(arr)
重新寫以上的條件語句。
function demo(fruit){
const redfruits = ['apple', 'strawberry', 'cherry', 'cranberries']
if(redfruits.includes(fruit)) {
console.log('red')
}
}
這裏我們使用一個輔助數組將 同一種顏色的水果放在了一個數組當中,這樣在使用 if
條件判斷的時候就簡介的多了。
當有多種顏色需要匹配多種水果的時候我們同樣可以使用輔助對象來實現我們的 if
條件的簡寫。
function demo (fruit) {
let fruitColor = {
red: ['apple', 'strawberry', 'cherry', 'cranberries'],
green: ['watermelon', 'pear']
}
object.keys(fruitColor).forEach(color => {
if(color.includes(fruit)) {
console.log('red')
}
})
}
Array.every /Array.some 處理全部滿足和部分滿足
- 檢查是否所有的水果都是紅色。
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
]
function demo () {
// every 返回是否同時滿足函數內條件
const isAllRed = fruits.every(fruit => fruit.color === 'red')
consolE.log(isAllRed) // false
}
- 檢查是否至少有一個水果是紅色。
function demo () {
const isAnyRed = fruits.some(fruit => fruit.color === 'red')
console.log(isAnyRed) //true
}