为什么Array.prototype.every在空数组上返回true? [英] Why does Array.prototype.every return true on an empty array?

查看:460
本文介绍了为什么Array.prototype.every在空数组上返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[].every(i => i instanceof Node) // -> true

为什么当数组为空时,JavaScript中数组上的每个方法都返回true。我正在尝试做类似的断言... ...

Why does the every method on arrays in JavaScript return true when the array is empty. I'm trying to do type assertion like so...

const isT = (val, str) => typeof val === str
const nT = (val, str) => !isT(val, str)
const is = {}

is.Undef = (...args) => args.every(o => isT(o, 'undefined'))
is.Def = (...args) => args.every(o => nT(o, 'undefined'))
is.Null = (...args) => args.every(o => o === null)
is.Node = (...args) => args.every(o => o instanceof Node)
is.NodeList = (...args) => args.every(n => n instanceof NodeList)

但即使没有参数,这些仍然会返回true传递给他们。

but these still return true even when no arguments are passed to them.

推荐答案

参见 docs


每个行为就像数学中的for all量词。特别是
,对于一个空数组,它返回true。 (真空是
,空集的所有元素都满足任何给定条件。)

every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

作为编辑,因为我看了真实的真相。我从上下文中理解它,但我对正式定义感兴趣。这个释义的例子说明了这个含义:

As an edit, because I looked Vacuous truth up. I understood it from context, but I was interested in the formal definition. This paraphrased quote exemplifies the meaning:


你是我最喜欢的侄子如果他只是那么这是一个空洞的陈述 nephew:没有其他人可以考虑。

"You are my favorite nephew" is a vacuous statement if he is the only nephew: there are no others to consider.

这篇关于为什么Array.prototype.every在空数组上返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆