[Intermediate Algorithm] - Everything Be True

题目

所有的东西都是真的!

完善编辑器中的every函数,如果集合(collection)中的所有对象都存在对应的属性(pre),并且属性(pre)对应的值为真。函数返回ture。反之,返回false。

记住:你只能通过中括号来访问对象的变量属性(pre)。

提示

提示:你可以有多种实现方式,最简洁的方式莫过于Array.prototype.every()

测试用例

  • 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

分析思路

  1. 判断是否对象包含属性,使用 Object.hasOwnProperty();
  2. 判断属性的值是否为真,直接使用 Object[pro] 即可;

代码

function every(collection, pre) {
  // Is everyone being true?
  return collection.every(function(element, index, array) {
    return (element.hasOwnProperty(pre) && element[pre]);
  });
}

every([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
posted @ 2017-05-25 16:49  water-moon  阅读(172)  评论(0编辑  收藏  举报