寫一個JS函數實現如下功能

問題1、

求一個JS函數能夠實現如下功能:

函數入參:一個數組,數組元素只能爲三種:{flag: true}{flag: false} 或者''
指望返回值:true或者false,知足:
1.數組元素只要有一個{flag: false},返回false
2.數組元素全爲'',返回false
3.數組元素非''的所有爲{flag: true},返回true數組

例如函數

const array1 = [{flag: true}, {flag: false},  ''; // 知足1,指望返回值false
const array2 = ['', '', '', '', '', '']; // 知足2,指望返回值false
const array3 = [{flag: true}, {flag: true},  '']; // 知足3,指望返回值true
const array4 = [{flag: true}, {flag: true},  {flag: true}]; // 知足3,指望返回值true

問題二

求一個JS函數能夠實現如下功能:

函數入參:一個數組(如下稱爲入參數組),數組元素只能爲三種:{flag: true}{flag: false} 或者''code

指望返回值:一個length爲2的數組(如下稱爲結果數組). 知足
1.結果數組的第一個元素爲入參數組index爲0、二、四、6等非奇數位元素組合符合問題一的返回值
1.結果數組的第二個元素爲入參數組index爲一、三、五、7等奇數爲元素組合符合問題一的返回值it

例如io

const array1 = [{flag: true}, {flag: true},  {flag: true}, '', {flag: false}]; 

非奇數位(index等於0,2,4)組合 [{flag: true}, {flag: true}, {flag: false}] // 根據問題一描述,結果false

奇數位爲(index等於1,3)組合 [{flag: true}, ''] // 根據問題一描述,結果爲true

指望返回值[false, true]

示例代碼

問題一:

function func (array) {
    let result = '';
    array.forEach((item) => {
        if (item !== '') {
            if (result === '') {
                result = item.flag;
            } else {
                result = result && item.flag;
            }
        }
    })
    return !!result;
}

問題二:

function func2 (array) {
    let result = ['', ''];
    array.forEach((item, index) => {
        if (item !== '') {
            if (result[index % 2] === '') {
                result[index % 2] = item.flag;
            } else {
                result[index % 2] = result[index % 2] && item.flag;
            }
        }
    });
    result.forEach(item => { item = item && true; })
    return result;
}

感受本身寫的過程太麻煩了,有沒有更簡單的寫法呢function

相關文章
相關標籤/搜索