Everything Be True
Check wheather collection has this property or not.題目會給予2個參數,第1個為一包含所有資料的array,第2個則為待檢測的性質,此題要求檢測array中所有Object(物件)都具有第2項參數的性質
function every(collection, pre) {
// Is everyone being true?
var allPass = true;
collection.forEach(function(emt)
{
if(!emt.hasOwnProperty(pre) || ( emt.hasOwnProperty(pre) && !emt[pre]) )
allPass = false;
});
return allPass;
}
every([{"user": "Tinky-Winky", "sex": "male"},
{"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
測試的正確結果
every([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") 應該返回 true。every([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") 應該返回 false。
every([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age") 應該返回 false。
every([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat") 應該返回 false
every([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat") 應該返回 true
every([{"single": "yes"}], "single") 應該返回 true
every([{"single": ""}, {"single": "double"}], "single") 應該返回 false
every([{"single": "double"}, {"single": undefined}], "single") 應該返回 false
every([{"single": "double"}, {"single": NaN}], "single") 應該返回 false
Solution:
P.S. / Reference: Object.prototype.hasOwnProperty()