JavaScript Essentials:如何使用if / else语句做出人生决定

Let’s say you’re walking on a busy street in the middle of town. You’re about to cross the road when you notice the traffic light for pedestrians turns red. What do you do?

假设您正在市区中间一条繁忙的街道上行走。 当您发现行人的交通灯变成红色时,您将要过马路。 你是做什么?

You stop, don’t you?

你停下来,不是吗?

And what happens when the light turns green again? You start walking.

当灯再次变绿时会发生什么? 你开始走路。

We can put this analogy into code, too. It sounds something like: “If the light turns red, stop walking. Otherwise, continue walking”.

我们也可以将此类比喻放入代码中。 听起来像是:“如果灯变成红色,请停止行走。 否则,请继续步行”。

And that, my friend, is the foundation of an if/else statement.

我的朋友,这就是if/else语句的基础。

if / else语句 (The if/else statement)

The if/else statement helps to control what your program does in specified situations. It looks like this:

if/else语句有助于控制程序在特定情况下的工作。 看起来像这样:

if (condition) {     // Do something } else {     // Do some other thing }

The condition tells JavaScript what to check for before continuing. If the condition evaluates to true, JavaScript executes the code within the if block.

condition告诉JavaScript在继续之前要检查什么。 如果条件评估为true ,则JavaScript将在if块内执行代码。

If the condition evaluates to false, JavaScript executes code from the else block.

如果条件评估为false ,则JavaScript从else块执行代码。

In the traffic light example, we check whether the light is red:

在交通信号灯示例中,我们检查信号灯是否为红色:

// Note: This example doesn't contain valid code yet if (light is red) {  stop walking } else {  continue walking }

If you need to check for more than one condition, you can use else if, which goes between if and else.

如果需要检查多个条件,则可以使用else if ,它介于ifelse之间。

When would you need such a second condition?

您什么时候需要第二种条件?

Well, let’s say you want to cross a small road. If there aren’t any cars around, would you wait for the traffic light to turn green? You still cross, don’t you?

好吧,假设您要穿越一条小路。 如果周围没有汽车,您会等待交通信号灯变绿吗? 你仍然穿越,不是吗?

In code, this would look like:

在代码中,这看起来像:

if (light is red) {   // Stop walking } else if (cars around) {   // Stop walking } else if (yet another condition) {   // Do yet another thing } else {   // Do the final thing }

In this case, if the first condition evaluates to true, JavaScript executes the code in the if block.

在这种情况下,如果第一个条件的值为true ,则JavaScript将在if块中执行代码。

If the first condition evaluates to false, JavaScript checks the condition in the next else if block and sees whether it evaluates to true. It goes on and on until all else if blocks are exhausted.

如果第一个条件的结果为false ,则JavaScript在下一个else if块中检查条件,并查看其条件是否为true 。 它会一直继续下去,直到所有else if块都用完为止。

To check whether a condition evaluates to true or false, JavaScript relies on two things:

要检查条件的评估结果是否为truefalse ,JavaScript依赖两件事:

  1. Comparison operators

    比较运算符
  2. Truthy and falsy values

    真实和虚假的价值观

Let’s talk about comparison operators first.

让我们先讨论比较运算符。

比较运算符 (Comparison operators)

There are four main types of comparison operators:

比较运算符主要有四种类型:

  1. Greater than (>) or greater or equal to (>=)

    大于( & gt;)或大于或等于t o (> =)

  2. Smaller than (&lt;) or smaller or equal to (<=)

    小于( & lt;)或小于或等于t o (<=)

  3. Strictly equal (===) or equal ==

    严格等于( === )或等于==

  4. Strictly unequal (!==) or unequal !=

    严格不相等( !== )或不相等!=

The first two types of comparison operators are straightforward. You use them to compare numbers.

前两种比较运算符很简单。 您可以使用它们来比较数字。

24 > 23 // True 24 > 24 // False 24 >= 24 // True
24 < 25 // True 24 < 24 // False 24 <= 24 // True

The next two types of comparison operators are quite straightforward as well. You use them to check whether things are equal or unequal to each other.

接下来的两种比较运算符也非常简单。 您可以使用它们来检查彼此是否相等。

24 === 24 // True 24 !== 24 // False

However, there’s a difference between strictly equal (===) vs equal (==), and strictly unequal (!==) vs unequal (!=):

但是,严格相等( === )与相等( == )和严格不相等( !== )与不相等( != )之间存在差异:

'24' === 24 // False '24' == 24 // True
'24' !== 24 // True '24' != 24 // False

As you can see from the example above, when you compare a string of 24 vs the number 24, === evaluates to false while == evaluates to true.

从上面的示例中可以看到,当比较字符串24和数字24时, ===false==为true。

Why is this so? Let’s look at the difference between strictly equal and equal.

为什么会这样呢? 让我们看一下严格相等和相等之间的区别。

=== vs ==(或!== vs!=) (=== vs == (or !== vs !=))

JavaScript is a loosely-typed language. What this means is that, when we declare variables, we don’t care what type of value goes into the variable.

JavaScript是一种松散类型的语言。 这意味着,当我们声明变量时,我们不在乎变量会使用哪种类型的值。

You can declare any primitive or object, and JavaScript does the rest for you automatically:

您可以声明任何原语或对象,JavaScript会自动为您完成其余工作:

const aString = 'Some string' const aNumber = 123 const aBoolean = true

When comparing things with strictly equal (===) or strictly unequal (!==), JavaScript checks the type of variable. This is why a string of 24 and a number 24 do not equate.

在比较严格等于( === )或严格不等于( !== )的事物时,JavaScript将检查变量的类型。 这就是为什么字符串 24数字 24不相等的原因。

'24' === 24 // False '24' !== 24 // True

When comparing things with equal (==) or unequal (!=), JavaScript converts (or casts) the types so they match each other.

比较具有相等( == )或不相等( != )的事物时,JavaScript会转换(或强制转换)类型,使它们彼此匹配。

Generally, JavaScript tries to convert all types to numbers when you use a conversion operator. In the example below, the string 24 is converted into the number 24 before the comparison.

通常,当您使用转换运算符时,JavaScript会尝试将所有类型转换为数字。 在下面的示例中, 字符串 24在比较之前转换为数字 24。

That’s why a string of 24 equates to a number of 24 when you use ==.

这就是为什么当使用==时,字符串24等于数字24的原因。

'24' == 24 // True '24' != 24 // False

Booleans can also be converted into numbers. When JavaScript converts Booleans into numbers, true becomes 1 and false becomes 0.

布尔值也可以转换为数字。 当JavaScript将布尔值转换为数字时, true变为1, false变为0。

0 == false // True 1 == true // True 2 == true // False

Automatic type conversion (when using comparison operators) is one of the common causes of hard-to-find bugs. Whenever you compare for equality, always use the strict versions (=== or !==).

自动类型转换(使用比较运算符时)是难以发现错误的常见原因之一。 每当您比较相等性时,请始终使用严格版本 ( ===!== )。

比较对象和数组 (Comparing objects and arrays)

Try comparing objects and arrays with === or ==. You’ll be very surprised.

尝试比较=====对象和数组。 你会很惊讶的。

const a = { isHavingFun: true } const b = { isHavingFun: true }
console.log(a === b) // false console.log(a == b) // false

In the example above, both a and b look exactly the same. They are both objects, they have the same values.

在上面的示例中, ab 看起来完全相同。 它们都是对象,它们具有相同的值。

The strange thing is, a === b is always going to be false. Why?

奇怪的是, a === b总是错误的。 为什么?

Let’s say you have an identical twin brother/sister. You look exactly the same as your twin. Same hair color, same face, same clothes, same everything. How can people differentiate the two of you? It’ll be hard.

假设您有一个相同的双胞胎兄弟姐妹。 你看起来和双胞胎完全一样。 相同的头发颜色,相同的面Kong,相同的衣服,相同的一切。 人们如何区分你们两个? 很难

In JavaScript, each object has an “identity card.” This identity card is called the reference to the object. When you compare objects with equality operators, you’re asking JavaScript to check if the two objects have the same reference (same identity card).

在JavaScript中,每个对象都有一个“身份证”。 此身份证称为对象的引用 。 当您将对象与相等运算符进行比较时,您要让JavaScript检查两个对象是否具有相同的引用(相同的身份证)。

Is it a surprise that a === b is always going to be false now?

a === b现在总是假,是否会感到惊讶?

Let’s tweak it a little and assign a to b.

让我们稍微调整一下,然后将a分配给b

const a = { isHavingFun: true } const b = a

In this case, a === b evaluates to true because b now points to the same reference as a.

在这种情况下, a === b的计算结果为真实的,因为b现在指向同一基准a

console.log(a === b) // true

真假 (Truthy and Falsy)

If you write a single variable (like hasApples in the example below) as the condition of an if/else statement, JavaScript checks for a truthy or a falsy value.

如果您编写一个变量(如下面示例中的hasApples )作为if/else语句的条件, if/else JavaScript将检查真值或伪值。

const hasApples = 'true'
if (hasApples) {   // Eat apple } else {   // Buy apples }

A falsy value is a value that evaluates to false when converted into a boolean. There are six possible falsy values in JavaScript:

伪造的值是当转换为布尔值时评估为false的值。 JavaScript中可能有六个伪造的值:

  1. false

    false

  2. undefined

    undefined

  3. null

    null

  4. 0 (numeric zero)

    0 (数字零)

  5. "" (empty string)

    "" (空字符串)

  6. NaN (Not A Number)

    NaN (非数字)

A truthy value, on the other hand, is a value that evaluates to true when converted into a Boolean. In the case of numbers, anything that’s not 0 converts to true.

truthy值,在另一方面,是计算结果为值true时转换成一个布尔值。 对于数字,任何非0将转换为true

Automatic type conversion to truthy and falsy values are highly encouraged in JavaScript, because they make code shorter and easier to comprehend.

在JavaScript中强烈建议将类型自动转换为true和falsy值 ,因为它们会使代码更短且更易于理解。

For example, if you want to check if a string is empty, you can use the string in the condition straightaway.

例如,如果要检查字符串是否为空,则可以直接在条件中使用该字符串。

const str = ''
if (str) {   // Do something if string is not empty } else {   // Do something if string is empty }

结语 (Wrapping up)

if/else statements are used to control what your program does in specific situations. It lets you determine whether to walk or cross the road, depending on the conditions given to you.

if/else语句用于控制程序在特定情况下的操作。 它使您可以根据所提供的条件确定是步行还是过马路。

To check if a condition is true or false, Javascript relies on two things:

要检查条件是对还是错,JavaScript依赖于两件事:

  1. comparison operators

    比较运算符
  2. truthy/falsy values

    真实/虚假价值观

If you loved this article, you’ll love learn Learn JavaScript — a course that helps you learn to build real components from scratch with Javascript. Click here to find out more about Learn JavaScript if you’re interested.

如果您喜欢这篇文章,那么您会喜欢学习JavaScript ,这是一门可以帮助您从头开始使用Javascript 构建实际组件的课程。 如果您有兴趣, 请单击此处以了解有关学习JavaScript的更多信息

(Oh, by the way, if you liked this article, I’d appreciate it if you could share it. ?)

(哦,顺便说一句,如果您喜欢这篇文章,如果可以分享的话 ,不胜感激。)

Originally published at zellwk.com.

最初在zellwk.com上发布。

翻译自: https://www.freecodecamp.org/news/javascript-essentials-how-to-make-life-decisions-with-if-else-statements-1908ff7cf5da/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值