javascript布尔值_JavaScript布尔值通过上法庭进行解释

javascript布尔值

by Kevin Kononenko

凯文·科诺年科(Kevin Kononenko)

JavaScript布尔值通过上法庭进行解释 (JavaScript booleans explained by going to court)

If you have ever watched a TV show about court (or been to court), then you can understand booleans in JavaScript.

如果您曾经看过关于法庭的电视节目(或去过法庭),那么您可以理解JavaScript中的布尔值。

You might think that booleans are the most straightforward topic that you could ask for in JavaScript.

您可能会认为布尔值是您在JavaScript中可能要求的最直接的主题。

After all, since a variable can be any of the following:

毕竟,由于变量可以是以下任意一种:

  • number

  • string

  • array

    数组
  • object

    目的
  • boolean

    布尔值

…boolean seems to be the easiest.

…布尔值似乎是最简单的。

let bool = true;
let bool= false;

The only two options for a boolean are true or false. And they are used in if() statements to decide which statement should be executed.

布尔值的唯一两个选项为true false 。 并且它们在if()语句中用于决定应执行哪个语句。

if(true){
}
else{
// if value is false, this block runs
}

But here’s the thing. Within if() statements, other variable values can evaluate to true or false. In other words, once the value is used in the if() statement, JavaScript will evaluate whether it is true or false.

但是,这就是事情。 在if()语句中,其他变量值可以评估为true或false。 换句话说,一旦在if()语句中使用了该值,JavaScript就会评估它是true还是false

For example, do you know if the value 0 is true or false?

例如,您知道值0是true还是false吗?

This is not a philosophy question. JavaScript has an answer.

这不是哲学问题。 JavaScript有一个答案。

Anyways, this happens because JavaScript is a weakly typed language. This means that in the context of an if() statement, it will convert other variable values to true or false in order to run the code. This is known as determining the “truthiness” of a value.

无论如何,发生这种情况是因为JavaScript是一种弱类型的语言。 这意味着在if()语句的上下文中,它将其他变量值转换为truefalse以便运行代码。 这被称为确定值的“真实性”。

Many other languages are strongly typed, so they will not convert values into true or false.

许多其他语言是强类型的 ,因此它们不会将值转换为true或false。

This may seem a little crazy, but it is actually pretty similar to the way that a judge in the United States determines whether an accused person is innocent or guilty. So, I can explain the way that “truthiness” and true/false works in JavaScript through legal rules that you have seen in “Law and Order” or any other court-based procedural dramas on TV.

这似乎有些疯狂,但实际上与美国法官确定被告是否无罪或有罪的方式非常相似。 因此,我可以通过您在《法律与秩序》或电视上任何其他基于法院的程序性戏剧中看到的法律规则,来解释JavaScript中“真实性”和“ true / false工作方式。

For the purposes of this tutorial, imagine that you are a district attorney that is trying to prosecute a person who is accused of stealing a car.

就本教程而言,假设您是一名地方检察官,正试图起诉被指控偷车的人。

And, you will need to understand the basics of variables in JavaScript to use this tutorial. Let’s get into it!

并且,您将需要了解JavaScript中变量基础才能使用本教程。 让我们开始吧!

JavaScript中的“真实性”是什么? (What is “truthiness” in JavaScript?)

In the United States, the criminal law system states that an accused person is “innocent until proven guilty”. That means that the burden lies on the prosecutor (you, in this case) to provide enough evidence to disprove the default assumption that the accused person is innocent.

在美国,刑法制度规定,被告“在被证明有罪之前是无辜的”。 这意味着,检察官(在本例中为您)有责任提供足够的证据,以驳斥被告无罪的默认假设。

In fact, the standard of evidence is “beyond a reasonable doubt.” This is consistent across many countries in the world.

实际上,证据标准是“ 毫无疑问的。 ”这在世界上许多国家都是一致的。

When we use if() statements, we are not always going to be able to plug in a variable with a value of true or false. Many times, we must plug in a statement that will be evaluated by JavaScript as true or false.

当我们使用if()语句时,我们并不总是能够插入值为truefalse的变量。 很多时候,我们必须插入一条语句,JavaScript会将其评估 true false

This is similar to the legal system! Although it is possible that there will be one piece of evidence that makes the “guilty” or “not guilty” verdict obvious, it is also likely that a judge or jury will need to evaluate multiple pieces of evidence and make a decision.

这类似于法律制度! 尽管可能有一个证据可以使“有罪”或“无罪”判决变得显而易见,但法官或陪审团也有可能需要评估多个证据并做出决定。

Let’s start with the basics. A true statement is evidence that will lead to the conviction of the accused. A false statement is evidence that will let them walk free. Let’s create a variable called evidence and set it to true.

让我们从基础开始。 true陈述是将导致被告定罪的证据。 false陈述是使他们自由行走的证据。 让我们创建一个称为evidence的变量并将其设置为 true

let evidence = true;
if (evidence){
convict();
}
else{
release();
}

convict() and release() are made-up functions. In this case, since evidence is set to true, the judge would convict the car thief. Here’s an interactive diagram of this scenario.

convict()release()是组合函数。 在这种情况下,由于证据被设置为true ,法官将定罪的偷车贼。 这是此方案的交互式图表。

The robber kinda looks like Edward Norton from “The Italian Job”, eh?

强盗有点像《意大利工作》中的爱德华·诺顿,是吗?

Anyways, in real life, it is never this straightforward. Let’s say that you have a killer piece of evidence — fingerprints from the car door. You present that to the judge.

无论如何,在现实生活中,从来没有这么简单。 假设您有一个杀手级的证据-车门上的指纹。 您将其提交给法官。

let evidence = "fingerprints";
if (evidence){
convict();
}
else{
release();
}

Aha! We only changed the first line, where we declared the variable evidence. And it is now a string rather than a boolean. But guess what? Due to type coercion, JavaScript will evaluate the string as true. Since there is no condition within the if() statement, all strings are true. We would run the convict() function!

啊哈! 我们只更改了第一行,在这里声明了可变证据。 现在它是一个字符串而不是布尔值。 但猜猜怎么了? 由于类型为强制 ,JavaScript会将字符串评估为 true 。 由于if()语句中没有条件,因此所有字符串均为true 。 我们将运行convict()函数!

真实性的例子 (Examples of truthiness)

Let’s imagine that instead, the evidence variable is set to 0. We run the same if() statement again.

让我们想象一下,取而代之的是将证据变量设置为0 。 我们再次运行相同的if()语句。

let evidence = 0;
if (evidence){
convict();
}
else{
release();
}

In this case, the statement would actually evaluate to false, and our accused car thief would be released.

在这种情况下,该声明实际上将为false ,并且我们的被指控小偷将被释放。

This is why it is called “truthiness” — because JavaScript is evaluating whether the condition is true or false.

这就是为什么将其称为“真实性”的原因-因为JavaScript正在评估条件是true还是false

Since the variable is set to 0, it’s kind of like if you were asked to present evidence against the thief, and you said… nothing.

由于变量设置为0 ,这有点像您被要求出示针对小偷的证据,而您却说……什么也没有。

Obviously the judge is going to determine you don’t have enough evidence, and set the person free! The same would happen if evidence was set to an empty string ``. You still aren’t offering anything, so your statement is evaluated as false.

显然,法官将确定您没有足够的证据,并让该人自由! 如果将证据设置为空字符串,也会发生同样的情况`` 。 您仍然没有提供任何东西,因此您的陈述被评估为false

let evidence = '';

Here’s one more test to see if you understand true versus false. What if the variable has not yet been initialized to a value?

这是另一个测试,以了解您是否了解truefalse 。 如果该变量尚未初始化为值怎么办?

let evidence;
if (evidence){
convict();
}
else{
release();
}

This is a pretty common one, because web developers will have another statement in their script that gives a value to the evidence variable. And, just like the two examples above, JavaScript will evaluate this variable as false if it does not have any value.

这是很常见的一种情况,因为Web开发人员的脚本中还会有另一条语句,该语句为evidence变量赋值。 并且,就像上面的两个示例一样,如果没有任何值,JavaScript会将此变量评估为false

This is a great example of “innocent until proven guilty”. The variable has not yet been assigned a value, so there is no way JavaScript could call it true.

这是“直到证明有罪之前无辜”的一个很好的例子。 该变量尚未分配值,因此JavaScript无法调用它 true

在if()语句中使用DOM元素 (Using DOM Elements in if() statements)

So we have covered values of variables that are “falsy”. But what about elements from the DOM?

因此,我们涵盖了“虚假”变量的值。 但是DOM中的元素呢?

Note: if you need a refresher, check out my guide to DOM elements here.

注意 :如果需要复习,请在此处查看我的DOM元素指南

In other words, what happens when we use a DOM element to determine which branch of an if/else statement to run? If you use jQuery or React (or Angular, and so forth), you probably manipulate the DOM in order to create a more dynamic interface.

换句话说,当我们使用DOM元素来确定要运行if/else语句的哪个分支时,会发生什么? 如果您使用jQuery或React(或Angular等),则可能会操纵DOM来创建更具动态性的界面。

In our courtroom example, let’s say that you swear that the lockpick the thief used is located in a trashcan near the crime scene. In HTML terms, you are saying that there is a div with ID lockpick somewhere in the DOM. How might the judge validate your claim?

在我们的法庭示例中,假设您发誓,小偷使用的密匙位于犯罪现场附近的垃圾桶中。 用HTML术语来说,您是说在DOM中某个地方有一个ID为lockpick的div。 法官如何验证您的主张?

if(document.getElementById('lockpick')){
convict()
}
else{
release()
}

Here’s an interactive image of that scenario.

这是该场景的交互式图像。

“Truthiness” here means that JavaScript will inspect the DOM, and only return true if it finds an element with ID lockpick. It’s kind of like a judge determining if the evidence that you present is real and authentic. In this case, it is, so the first block of code will run, and the person will be convicted.

这里的“正确性”意味着JavaScript将检查DOM,并且只有在找到具有ID lockpick的元素时才返回true 。 这就像法官判断您提供的证据是否真实真实。 在这种情况下,第一个代码块将运行,此人将被定罪。

This is super useful! We have now extended the concept of true so that it includes whether an element exists or not. This logic also applies to objects and arrays. You can check whether an element with a specific class exists, whether a certain element has children, you get the idea.

这超级有用! 现在,我们扩展了true的概念 这样它就包括一个元素是否存在。 此逻辑也适用于对象和数组。 您可以检查是否存在具有特定类的元素,或者某个元素是否具有子元素,您就会明白。

if()语句的更多变体 (More variations of if() statements)

When you bring an accused person to court, they may still be convicted of a lesser crime. If you don’t have enough evidence for the main charge, they can still be convicted of a lower charges.

当您将被告告上法庭时,他们仍然可能被判犯有较小的罪行。 如果您没有足够的证据证明主要指控,他们仍可能被判较低的指控。

In the example of car theft, there is a breaking and entering crime, and then theft is possible if the accused person has already broken into the car.

在偷车的例子中,有闯入和闯入犯罪的行为,如果被告已经闯入汽车,则可能发生盗窃。

We can combine if(), else if(), and else() to model these options. Let’s say the accused person did break into the car, but did not take anything. We could model the options like this:

我们可以结合使用if()else if()else()来对这些选项进行建模。 假设被告确实闯入汽车,但没有带任何东西。 我们可以像这样对选项建模:

let breaking = true;
let theft = false;
if (breaking && theft){
convict('felony');
}
else if(breaking){
convict ('misdemeanor');
}
else{
release();
}

There are now three scenarios. If the first condition is satisfied, that code block will run. That means that the thief would be convicted of a felony. But, if only the value of the variable breaking can be evaluated as true, the person will still be convicted of a misdemeanor.

现在有三种情况。 如果满足第一个条件,则该代码块将运行。 这意味着小偷将被判重罪。 但是,如果仅将变量breaking的值评估为true ,则该人仍将被判轻罪。

The judge is saying, “You need to show me evidence of both breaking and entering and theft if I am going to convict this person of a felony.”

法官说:“如果我要定罪此人重罪,则需要向我显示闯入盗窃的证据。”

The first if() statement will evaluate true && false, which will be reduced to false since false takes precedence over true (remember, innocent until proven guilty).

第一个if()语句将对true && false进行评估,由于false优先于true (记住,直到证明有罪之前是无辜的),这将减少为false

This would still work if we used values that were “truthy” or “falsy”. Each one would be evaluated to true or false within the if() statement, and then JavaScript would decide which block to execute.

如果我们使用“真实”或“虚假”的值,则此方法仍然有效。 在if()语句中,每个值都将被评估为truefalse ,然后JavaScript将决定执行哪个块。

获取更多视觉教程 (Get more visual tutorials)

Did you enjoy this guide? Give it a “clap”, or sign up below to get my latest tutorials on web development topics.

您喜欢本指南吗? 给它一个“掌声”,或在下面注册以获取有关Web开发主题的最新教程。

翻译自: https://www.freecodecamp.org/news/javascript-booleans-explained-by-going-to-court-a0ca1149a0dc/

javascript布尔值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值