2017-06-14 58 views
0

我遇到了FreeCodeCamp的Intermediate Algorithm Scripting部分的Everything Be True問題。這個挑戰的目標是「檢查謂詞(第二個參數)是否真的對一個集合的所有元素(第一個參數)freeCodeCamp一切都是真的算法,未定義輸出

我遇到的問題是我的代碼輸出」未定義「某些輸入,但我看不出有任何理由爲什麼它是這樣做的。我的代碼如下...

function truthCheck(collection, pre) { 
    var answer; 
     var filtColl = collection.filter(function(val) { 
return val.hasOwnProperty(pre); 
    }); 
    if (filtColl.length !== collection.length) { 
    answer = false; 
    } else { 
for (var i = 0; i < filtColl; i++) { 
    if (filtColl[1][pre] === 0 || filtColl[i][pre] === null || filtColl[i][pre] === "" || filtColl[i][pre] === undefined || filtColl[i][pre] === NaN) { 
    answer = false; 
    } else { 
    answer = true; 
    } 
    } 
} 
return answer; 
} 
    console.log(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": 
"Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": 
"Po", "sex": "female"}], "sex")); 
    console.log(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": 
"Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": 
"female"}], "sex")); 
    console.log(truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, 
{"user": "Dipsey", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": 
"female", "age": 5}, {"user": "Po", "sex": "female", "age": 4 }], "age")); 
    console.log(truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", 
"onBoat": true}, {"name": "FastForward", "onBoat": null}], "onBoat")); 

第二屆的console.log正確輸出爲「假」,但其他三個輸出爲「不確定。」我不能爲我的生活找出爲什麼我的代碼不工作任何想法?

回答

0
function truthCheck(col, pre) { 

    return col.every(function(val) { 
    return val[pre]; 
    }); 

} 

這是一個很簡單的方法:)它基本上根據每個對象是否包含與第二個參數相匹配的屬性都返回true或false。

你甚至可以縮短到這個:)

truthCheck = (col, pre) => col.every(val => val[pre]);