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.

布尔值的唯一两个选项为truefalse 。 并且它们在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布尔值

javascript布尔值_JavaScript布尔值通过上法庭进行解释相关推荐

  1. javascript 布尔_JavaScript布尔说明-如何在JavaScript中使用布尔

    javascript 布尔 布尔型 (Boolean) Booleans are a primitive datatype commonly used in computer programming ...

  2. java布尔值_Java中的布尔值与布尔值

    HUX布斯 我有点扩展了提供的答案(因为到目前为止,他们专注于他们自己的"自己的" /人工术语,侧重于对特定语言进行编程,而不是照顾一般情况下(即当事情发生时)创建编程语言的幕后情 ...

  3. java中布尔型常量的值分别是 和,Java中用0和非0的数字表示布尔类型常量的值

    Java中用0和非0的数字表示布尔类型常量的值 答:× 创始人和其他创业合伙人最有可能在什么阶段开诚布公地友好协商股权架构设计和股权分配问题 答:创业企业初创期 微型计算机的主频是衡量计算机性能的重要 ...

  4. Python进阶之路 3.4.1 布尔值和布尔变量

    3.4.1 布尔值和布尔变量 在讲条件语句之前,首先应该了解一下布尔(boolean)类型.条件语句(if)需要为其制定布尔值或布尔类型的变量,才能根据条件判断是否要执行指定代码块中的语句.布尔值只有 ...

  5. Python中的布尔类型以及布尔值介绍

    什么是布尔类型? 布尔类型是一种逻辑类型,它只有两个取值:True(真)和False(假).在Python中,True和False是内置的布尔类型常量,用于表示真和假的状态. 布尔运算符 在Pytho ...

  6. 2.8 将一个整型变量的值赋给一个布尔型变量,再将这个布尔型变量的值赋给一个整型变量,得到的值是多少?

    试题描述 将一个整型变量的值赋给一个布尔型变量,再将这个布尔型变量的值赋给一个整型变量,得到的值是多少? 输入格式 一个整型范围内的整数,即初始时整型变量的值. 输出格式 一个整数,经过上述过程后得到 ...

  7. c语言 函数返回布尔值,返回值为布尔值

    java中 返回值为boolean的函数的默认返回值是什么 定义了一个返回值为boolean的函数,比如public boolean foo(), 如果在boolean的函数的默认返回值是return ...

  8. java 定时器返回值_javascript 函数返回值(return)、定时器(setTimeout、setInterval)...

    一.函数的返回值:return 1.函数名+括号=return后面的值 function fn1(){ return 100; } alert(fn1()); // 100 fn1()=return后 ...

  9. async js 返回值_获取JavaScript异步函数的返回值

    今天研究一个小问题: 怎么拿到JavaScript异步函数的返回值? 1.错误尝试 当年未入行时,我的最初尝试: function getSomething() { var r = 0; setTim ...

最新文章

  1. ORB-SLAM2从理论到代码实现(七):Tracking.cc程序详解(中)
  2. 字节跳动学习笔记:java实例变量和静态变量
  3. 手把手玩转win8开发系列课程(18)
  4. JDK的环境变量配置
  5. css实现tab切换效果
  6. 定制ListView的界面(使用自定义的列表项布局,一边显示水果图片,一边显示水果文字)以及ListView的点击事件
  7. 1.8 Arrays工具类
  8. github的watch和star的位置
  9. 开平推进智慧城市等领域信息化建设及公共数据资源共享
  10. 我的网站恢复访问了,http://FansUnion.cn
  11. 电脑dns_女生也能学会的修电脑技巧
  12. java实例摘要(二)
  13. down.php怎么安装,Markdown、phpstudy的安装及配置
  14. 菲律宾php是啥,投资菲律宾马尼拉房产的本质是什么?
  15. Excel 常用函数和公式
  16. Bootstrap 框架-下拉菜单
  17. python 时间模块判断上午还是下午_Python的时间模块小结(转自:不懂真人)
  18. CV之IE之Inception:基于TF框架利用Inception模型+GD算法的某层网络图像生成不同尺寸和质量的Deep Dream幻觉梦境图片(特征可视化实现图像可解释性)—五个架构设计思维导图
  19. 手把手教你在阿里云服务器上安装Java环境(图文教程)
  20. Sea-thru: A Method For Removing Water From Underwater Images论文研读

热门文章

  1. xCode 安装Mobile Device Framework出错的问题的解决方法
  2. python3解释器安装过程 2022
  3. ktv 上传图片 1218
  4. 用户管理 之 Linux 系统中的超级权限的控制
  5. 企业级 SpringCloud 教程 (七) 高可用的分布式配置中心(Spring Cloud Config)
  6. PCB中英对照一、 综合词汇
  7. 抓到的一次suse11 xen用libvirt连接的错误
  8. JavaScript indexOf() 方法
  9. iOS:Covert p12 back to CSR
  10. JSON for java入门总结