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:

依照題目要求檢查所有Object,所以用forEach來訪問array中每個Object,並用hasOwnProperty()函數來檢查是否擁有該性質,該函數會回傳該物件是否擁有該屬性的狀況,擁有⇒true、不具有⇒false,藉此判斷是否擁有題目要求的性質,但有些test case中的資料形式({"Property" : "value"})中property的key所對應的value為0、NaN(Not a Number)、null、undefined、''(空字串)等等的值,此類的Property雖然用hasOwnProperty檢測得出Property,但是其對應值卻是無效的或不存在的,所以判斷式為if(!emt.hasOwnProperty(pre) || ( emt.hasOwnProperty(pre) && ! emt[pre]) ) ,其中OR前面為判斷性質是否存在的邏輯(使用了! -反向符號(not) ),將真假值調換,也就是原本為fasle的值轉變為真,好讓if直接依據真假值判斷不必再寫equal false的判斷,以及當為false可直接進入if成立的區塊中執行動作,相當方便),而OR後面那項則為當Property存在,但其對應的value值無效時的邏輯(一樣使用反向符號(not)來將原來false轉為true來節省後續須寫的代碼),如果不使用此方法則必須寫成emt[pre]=== NaN、emt[pre]=== undefined ...等,會多出5個判斷式(0、NaN(Not a Number)、null、undefined、''(空字串))



P.S. / Reference:  Object.prototype.hasOwnProperty()

results matching ""

    No results matching ""