【FCC】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

代码:

<script type="text/javascript">
	function every(collection, pre) {
		// Is everyone being true?
		var flag = true;
		for (var i in collection) {
			// console.log(collection[i]);
			if (!collection[i][pre]) {
				flag = false;
			}
		}
		return flag;
	}
</script>

 

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注