快速判斷數(shù)組中的任意一個(gè)元素是否包含某個(gè)值

實(shí)際在使用js進(jìn)行編程中經(jīng)常會有要判斷一個(gè)數(shù)組是否有任意一個(gè)子元素包含或者符合某個(gè)條件,只有任意一個(gè)符合,則返回true或者false,或者要全部符合才返回true或者false。

在js中有提供兩個(gè)方法來實(shí)現(xiàn),分別是every和some。主子節(jié)點(diǎn)的選中為例。

1.子節(jié)點(diǎn)都未選中,則主節(jié)點(diǎn)應(yīng)該為未選中。

子節(jié)點(diǎn)都未選中,則主節(jié)點(diǎn)應(yīng)該為未選中

let data = {

    text: 'Check all',

    checked: '待定',

    children: [{

        text: 'Apple',

        checked: false,

    },{

        text: 'Pear',

        checked: false,

    },{

        text: 'Orange',

        checked: false,

    }]

}

此時(shí)在Check all中的待定應(yīng)該使用 every 方法進(jìn)行判斷,只要children中的所有的checked都為false,則Check all的checked則應(yīng)該是false。


// 判斷未選中,判斷所有children的checked為false,若都為false,every返回true,則主節(jié)點(diǎn)為未選中狀態(tài)。

data.checked = data.children.every(e => {

return e.checked === false

}) ? fasle : true

2.子節(jié)點(diǎn)部分選中或者全部選中,則主節(jié)點(diǎn)應(yīng)該選中。(部分選中的話,主節(jié)點(diǎn)的應(yīng)該有區(qū)分與全部選中的顯示方式,可見第3點(diǎn))

子節(jié)點(diǎn)全部選中,則主節(jié)點(diǎn)應(yīng)該選中

let data = {

    text: 'Check all',

    checked: '待定',

    children: [{

        text: 'Apple',

        checked: true,

    },{

        text: 'Pear',

        checked: true,

    },{

        text: 'Orange',

        checked: true,

    }]

}

此時(shí)在Check all中的待定應(yīng)該使用 some 方法進(jìn)行判斷,只要children中的任意一個(gè)子元素的checked都為true,則Check all的checked則應(yīng)該是true。


data.checked = data.children.some(e => {

return e.checked === true

}) ? true : false

3.子節(jié)點(diǎn)部分選中,則主節(jié)點(diǎn)應(yīng)該選中,但應(yīng)該有個(gè)標(biāo)注為未完全選中狀態(tài)。(暫定未用indeterminate來表示狀態(tài))

子節(jié)點(diǎn)部分選中,則主節(jié)點(diǎn)應(yīng)該為未完全選中

let data = {

    text: 'Check all',

    checked: true,

indeterminate: '待定',

    children: [{

        text: 'Apple',

        checked: false,

    },{

        text: 'Pear',

        checked: true,

    },{

        text: 'Orange',

        checked: false,

    }]

}

此時(shí)在Check all中的待定應(yīng)該使用 some 或者 every 組合判斷,只要children中的任意一個(gè)子元素的checked包含true和false或者不全都為true或者false,則Check all的indeterminate為true


// 使用some方法

data.indeterminate = (data.children.some(e => {

return e.checked === true

}) && data.children.some(e => {

return e.checked === false

}))? true : false

// 使用every方法

data.indeterminate = (!data.children.every(e => {

return e.checked === true

}) && !data.children.every(e => {

return e.checked === false

}))? true : false

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容