Array.every()检查值是否为false

时间:2017-12-28 21:25:17

标签: javascript

我有一个这样的数组:

   myArray = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false};

我想检查每个值是否为false,如果是,请执行某些操作。 示例:

  myArray.every(x => x==false)
  //do something

这是正确的方法吗?还是需要传递一个功能?

4 个答案:

答案 0 :(得分:4)

<强>第一即可。它不是数组,它是对象

如果您想检查所有值是否为false,您可以通过Object#keys获取密钥,然后在该阵列上使用Array#every

&#13;
&#13;
const obj = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false};

const allFalse = Object.keys(obj).every(key => obj[key] === false);

console.log(allFalse);
&#13;
&#13;
&#13;

如果您使用ES8,则还可以使用Object#values

&#13;
&#13;
const obj = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false};

const allFalse = Object.values(obj).every(value => value === false);

console.log(allFalse);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

你没有数组,你有一个对象

可以使用Object.values()创建要迭代的值数组

Object.values(myArray).every(x => x===false)

如果在旧版浏览器中使用

,请注意需要填充

答案 2 :(得分:0)

我愿意:

 !Object.values(myArray /*?*/).reduce((a,b) => a || b);

答案 3 :(得分:0)

除了使用Array#every之外,您还可以使用Array#some并使用logical NOT !作为回调来获取Boolean的值。

$ hg mv --help
hg rename [OPTION]... SOURCE... DEST

aliases: move, mv

rename files; equivalent of copy + remove

    Mark dest as copies of sources; mark sources for deletion. If dest is a
    directory, copies are put in that directory. If dest is a file, there can
    only be one source.

    By default, this command copies the contents of files as they exist in the
    working directory. If invoked with -A/--after, the operation is recorded,
    but no copying is performed.

    This command takes effect at the next commit. To undo a rename before
    that, see 'hg revert'.

    Returns 0 on success, 1 if errors are encountered.

options ([+] can be repeated):

 -A --after               record a rename that has already occurred
 -f --force               forcibly copy over an existing managed file
 -I --include PATTERN [+] include names matching the given patterns
 -X --exclude PATTERN [+] exclude names matching the given patterns
 -n --dry-run             do not perform actions, just print output
    --mq                  operate on patch repository

(some details hidden, use --verbose to show complete help)