• [Intermediate Algorithm]


    题目

    所有的东西都是真的!

    完善编辑器中的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");
    
  • 相关阅读:
    [leetcode] Valid Sudoku
    [leetcode] Count and Say
    [leetcode] Decode Ways
    [leetcode] Sqrt(x)
    [leetcode] Best Time to Buy and Sell Stock II
    7-27 兔子繁衍问题
    7-26 最大公约数和最小公倍数
    7-25 求奇数和
    7-24 猜数字游戏
    7-23 分段计算居民水费
  • 原文地址:https://www.cnblogs.com/water-moon/p/6904718.html
Copyright © 2020-2023  润新知