题目
所有的东西都是真的!
完善编辑器中的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
分析思路
- 判断是否对象包含属性,使用
Object.hasOwnProperty()
; - 判断属性的值是否为真,直接使用 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");