JavaScript:当 `ternary` 或 `if` 语句的 `condition` 部分不包括 `===` 或 `>=`

JavaScript: When the `condition` portion of a `ternary` or `if` statement does not include `===` or `>=`

在以下 ternary 语句的 condition 部分中,playlist.length 是否等于 playlist.length >= 1

var playlist = ["video1", "video2", "video3", "video4", "video5"];

// some code here

alert ((playlist.length) ?
     playlist.length + "video(s) remain in the playlist: " + playlist.join (", ") + "." 
    : "No videos remain in the playlist");

同样,在下面的代码片段中,! playlist.length 是否等于 playlist.length === 0

alert ((! playlist.length) ?
     "No videos in the playlist."
    : playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + ".");

This is the first time I've seen an example where the condition portion of a ternary or if statement does not include such a notation as === or >=. So I'm not sure how to interpret this.

? 左边的部分只是计算“truthiness”。值 0 是 "falsy" 因此为了测试的目的评估为 false。 0 以外的数值为 "truish",因此为此目的评估为真。

三元的所有其他行为都是相同的。

===!== 只是添加了附加约束,即 L 值和 R 值也必须是同一类型。

0 在 JavaScript 中的布尔比较中隐式转换为 false。所以当长度为0时,即为假。相反,在 JavaScript 中的布尔比较中,任何其他数字都将隐式转换为 true。所以当长度不是 0 时它是真的。

一个简单的测试是使用 !! 查看 "truthy" 值

!!1 === true
!!0 === false
!!6 === true

在 javascript 中,0 等于 false,任何其他数值等于 true,但如果您使用 ===,它也会比较值类型。

两者非常相似:!playlist.lengthplaylist.length === 0

但是,它们并不完全相同。其实这里:

var playlist1 = [];
var playlist2 = {};
!playlist1.length // true
!playlist2.length // true
playlist1.length === 0 // true
playlist1.length === 0 // false

从这个意义上说 !playlist.length 也可以用于所有类型的对象,而不仅仅是数组。

无论如何,在数组上使用它时,它是一种检查数组是否为空的方法,并且按照您的建议工作,与 playlist.length === 0 相同。