This article is a beginner's introduction to JavaScript conditionals. It covers why we need them, and how they fit into the front-end context. And why you will end up using them regularly.

本文是JavaScript条件语句的初学者介绍。 它涵盖了我们为什么需要它们,以及它们如何适应前端环境。 以及为什么最终会定期使用它们。

介绍 (Introduction)

I came into development from a non-traditional path. One thing was always particularly hard – to be able to go beyond the syntax of a new concept and place it in a context that made sense.

我从非传统的道路发展。 一件事总是特别困难–能够超越新概念的语法并将其置于有意义的环境中。

Conditionals are a little more intuitive than other concepts, but I want to show you the big picture. In this article, I'll explain why we need conditionals and how we can use them as front-end developers.

条件句比其他概念更直观,但是我想向您展示大局。 在本文中,我将解释为什么需要条件,以及如何将其用作前端开发人员。

With the help of a beginner-friendly practical example, you'll see how you can use conditionals to process data in different ways and why they're a fundamental tool in development. Feel free to follow along while reading through this article.

在一个适合初学者的实用示例的帮助下,您将看到如何使用条件以不同的方式处理数据,以及为什么它们是开发中的基本工具。 请随时阅读本文。

The only prerequisite is a basic understanding of arrays and loops. I've covered those in two previous articles:

唯一的前提条件是对数组和循环有基本的了解。 我已经在前两篇文章中介绍了这些内容:

Arrays: https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-array/

数组 : https : //www.freecodecamp.org/news/what-in-the-world-is-a-javascript-array/

Loops: https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-loop-for/

循环 : https : //www.freecodecamp.org/news/what-in-the-world-is-a-javascript-loop-for/

设置 (The setup)

Let’s imagine that we are working on an online platform that allows us to do our grocery shopping from a website. That's a real-world application of the things we want to talk about here.

假设我们正在一个在线平台上工作,该平台使我们能够从网站上进行杂货店购物。 这是我们要在此处讨论的事情的真实应用。

Take a look at Lola Market, which is where I work, for an example of what this would look like.

看一看我工作的劳拉市场 ,举个例子。

In the example we set up in the previous articles, we took a bunch of products (mushrooms, steak, fish, aubergines, and lentils) and organised them inside an array. We then stored that array as a variable and used a forEach loop to iterate over the list.

在上一篇文章中设置的示例中,我们采用了一堆产品(蘑菇,牛排,鱼,茄子和小扁豆)并将它们组织在一个数组中。 然后,我们将该数组存储为变量,并使用forEach循环遍历列表。

We are assuming that this list of products is now displayed on our website. Our task is to add a "(v)" next to vegetarian items on this list. This is just the kind of thing we regularly do on the front end.

我们假设此产品列表现在显示在我们的网站上。 我们的任务是在此列表的素食食品旁边添加“(v)”。 这只是我们经常在前端执行的操作。

有条件的 (Conditionals)

Conditionals are essential building blocks of programming. They are a way to do something only if certain conditions are met. The simplest and most common conditional in JavaScript is the if statement. Take a look at an example:

条件是编程的基本组成部分。 只有满足某些条件,它们才是做某事的一种方式。 JavaScript中最简单,最常见的条件是if语句。 看一个例子:

if (product === 'steak') {// do stuff
}

Let’s start by translating this to English: “If the variable called product is exactly the string of characters 'steak' then execute the code within.”

让我们首先将其翻译成英文:“如果名为product的变量恰好是'steak'字符串,则在其中执行代码。”

Here’s a closer look

仔细看看

  • if: This is the conditional.

    if :这是有条件的。

  • (product === ‘steak’): This is our condition. There are a lot of ways you can construct conditions. We don’t need to worry about this yet. For now, bear in mind that whatever we put here will always be evaluated to either true or false.

    (product === 'steak') :这是我们的情况。 有很多方法可以构造条件。 我们现在不必为此担心。 现在,请记住,无论我们在此处输入什么内容,都将始终将其评估为truefalse

  • // do stuff: The statement. This is where the code we want to run goes. It will be executed only if the result of the evaluation of the condition is true. Otherwise, it will be ignored.

    // do stuff :该语句。 这就是我们要运行的代码所在的位置。 当条件评估的结果为true 时才执行。 否则,它将被忽略。

This bit of code will work on its own just fine, but we can have much more detailed control by using its friends  else if and else. else if adds another condition to check and executes another separate block of code, while else becomes the default action to take if none of the conditions are met.

这段代码本身可以很好地工作,但是我们可以通过使用else ifelse朋友来进行更详细的控制。 else if添加了另一个条件来检查并执行另一个单独的代码块,则else成为所有条件都不满足时要采取的默认操作。

提供素食 (Vegetarian Friendly)

Let’s focus back on our original objective, which is to log a “(v)” next to the name of vegetarian items. This is a prime example of when we need to use a conditional. We want code that, if the product in the array is vegetarian, to print its name and add to it the “(v)”. And if it’s not vegetarian, to only print the name of the product.

让我们重新回到最初的目标,即在素食名称旁边写上“(v)”。 这是何时需要使用条件语句的主要示例。 我们想要的代码是, 如果数组中的product 素食的,则打印其名称并在其上添加“(v)”。 如果不是素食主义者,请仅打印product名称。

First, we need to identify vegetarian items. Normally this information will be included with the data we requested from our database. But since we are using a simplified example, we will do it manually. We know that steak and fish are not vegetarian.

首先,我们需要确定素食。 通常,此信息将包含在我们从数据库请求的数据中。 但是,由于我们使用的是简化示例,因此我们将手动执行。 我们知道牛排和鱼不是素食主义者。

Notice, the condition I’m testing is if a product is not vegetarian. This is only because there are more vegetarian products on this list and I want the condition to be simple and the conditional to do the least amount of work. I could have just as easily tested for vegetarian items instead.

请注意,我要测试的条件是产品是否不是素食主义者。 这仅是因为此清单上有更多的素食产品,我希望条件简单,有条件的工作量最少。 我本来可以很容易地测试素食项目。

There are often many conditions that can be used to achieve the same goal. Writing good conditions that are efficient and readable is a useful skill that comes with practice.

通常可以使用许多条件来实现相同的目标。 编写有效且易读的良好条件是实践附带的有用技能。

So let’s write the condition that separates vegetarian from non-vegetarian.

因此,让我们写下将素食与非素食区分开的条件。

if (product === 'steak' || product === 'fish') {console.log(product)
} else {console.log(product + '(v)')
}

Following on from the example in my previous articles (linked above) we want to place the conditional inside the loop. The loop gives us each product in the list to process individually. This conditional block is the code that we are executing for each product in our array of products now.

在我之前的文章(上面链接)中的示例之后,我们希望将条件放在循环中。 循环使我们可以使用列表中的每个产品进行单独处理。 此条件块是我们现在为产品数组中的每个产品执行的代码。

Refresh the browser to start with a fresh console, then enter the following:

刷新浏览器以使用全新的控制台启动,然后输入以下内容:

  • The variable product storing our array of products.

    可变product存储我们的产品系列。

  • The forEach loop iterating over the array.

    forEach循环遍历数组。

  • And our conditional block inside.还有我们的条件块。

执行 (Execution)

If we read the conditional code in plain English it says: “If the currently selected product is exactly ‘steak’ or ‘fish’ then log product to the console. Otherwise, in all other cases log product to the console but also add a string “(v)” to the end of it.”

如果我们读简单的英语 ,它说的条件代码:“ 如果当前选择的product 完全‘牛排’ ‘鱼’然后登录product到控制台。 否则,在所有其他情况下,请将product记录到控制台,但还要在其末尾添加字符串“(v)”。

Quick note, the === operator checks that the left and right expressions are exactly the same. and the || operator means or. We have two conditions to check here (steak or fish). If either of the two conditions is true it will execute the code within.

快速说明, ===运算符将检查左右表达式是否完全相同 。 和|| 运算符意味着或。 我们有两个条件要检查(牛排或鱼) 如果两个条件中的任何一个为真,它将在其中执行代码。

Hit enter to run the code and see the results.

按Enter键以运行代码并查看结果。

And there it is. Every time the loop runs, it checks the currently selected element product and goes through the conditionals.

在那里。 每次循环运行时,它都会检查当前选定的元素product并通过条件。

  • Is product exactly the string ‘steak’?

    product是字符串“ steak”吗?

  • No. Check the following condition.否。检查以下情况。
  • Is product exactly the string ‘fish’?

    product确切是字符串“ fish”吗?

  • No. This condition is not met, the code inside will not execute. Go to the default code specified in the else block.

    否。不满足此条件,因此内部代码将无法执行。 转到else块中指定的默认代码。

  • Print product and add (v) to it.

    打印product并添加(v)

  • This iteration is finished. Start the next iteration.此迭代已完成。 开始下一个迭代。

If it finds ‘steak’ or ‘fish’ it will execute the code within that condition logging the product name without the "(v)". Then the loop finishes that iteration and starts the next, and so on. This process repeats for each element in the array until it’s all completed and the loop has logged the correct message for each one.

如果找到“牛排”或“鱼”,它将在该条件下执行代码,记录不带“(v)”的product名称。 然后循环完成该迭代并开始下一个迭代,依此类推。 对数组中的每个元素重复此过程,直到完成所有操作,并且循环为每个元素记录了正确的消息。

结论 (Conclusion)

To recap, a conditional statement sets certain conditions. When met (which means when the condition evaluates to true) the code specified inside the conditional block executes. Otherwise, it is ignored and not executed.

回顾一下, 条件语句设置了某些条件。 当满足时(这意味着条件评估为true ),将执行条件块中指定的代码。 否则,它将被忽略并且不执行。

In our example, we have only logged messages to the console. But we can use the same idea to manipulate the DOM to display and modify content on a website.

在我们的示例中,我们仅将消息记录到控制台。 但是我们可以使用相同的想法来操纵DOM以显示和修改网站上的内容。

Here are a few things you will need to further expand your knowledge and understand these concepts more in-depth:

您需要做一些事情来进一步扩展您的知识并更深入地理解这些概念:

  • Conditionals: The if statement is one of the most commonly-used conditionals. But you will need to learn about others like the while statement, the switch statement, or the very useful ternary operator.

    条件语句 if语句是最常用的条件语句之一。 但是您将需要了解其他信息,例如while语句, switch语句或非常有用的三元运算符

  • Conditions: Understand how to create conditions and how they are evaluated. For that, you need to become familiar with the concepts of “truthy” and “falsy”. This is when values that are not explicitly true or false are evaluated as such.  For example, a string like 'mushrooms' is considered true whereas an empty string '' is always considered false.

    条件:了解如何创建条件以及如何对其进行评估。 为此,您需要熟悉“ 真实 ”和“ 虚假 ”的概念。 在这种情况下,对不显式为truefalse的值进行评估。 例如,像'mushrooms'这样的字符串被认为是true,而空字符串''始终被认为是false。

  • Logical operators and comparison operators: We saw those in our conditions. Logical operators like “and” and “or”, written && and ||. Comparison operators like “equals” and “greater than”, written === and >. These are simple concepts that are the bread and butter of writing code.

    逻辑运算符和比较运算符:我们看到了我们所处的条件。 逻辑运算符,如“ 和” ,“ 或” ,写为&&|| 。 比较运算符,例如“等于”“大于” ,写成===> 。 这些都是简单的概念,它们是编写代码的基础。

关闭 (Closure)

Thanks for reading. I hope you found this useful. And if you enjoyed it, sharing it around would be greatly appreciated. If you have any questions or comments I’m on Twitter @Syknapse and I would love to hear from you.

谢谢阅读。 希望您觉得这有用。 并且,如果您喜欢它,与周围分享它将不胜感激。 如果您有任何疑问或意见,我在Twitter @Syknapse上 ,我希望收到您的来信 。

My name is Syk and I’m a front-end developer at Lola Market in Madrid. I career-changed into web dev from an unrelated field, so I try to create content for those on a similar journey. My DMs are always open for aspiring web developers in need of some support. You can also read about my transformation in this article.

我叫Syk,是马德里Lola Market的前端开发人员。 我从一个无关领域转变为Web开发人员,因此我尝试为类似旅程中的人员创建内容。 我的DM总是向有需要的Web开发人员开放。 您还可以在本文中了解有关我的转换的信息 。

翻译自: https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-conditional-for/

世界上有条件JavaScript是什么?相关推荐

  1. 想听世界上最懂 JavaScript 的人和你讲JavaScript 吗?

    时至今日,JavaScript 对前端工程师的重要性已无需多言.甚至有些同学已经达到了通读语言标准,对 ECMA-262 规范熟捻于心的水平. 然而即便如此,很多同学仍然将编程语言作为一种源自权威的. ...

  2. 在别人网页上运行js脚本_初始JavaScript,世界上最流行的语言之一

    1.JavaScript 是什么? JavaScript 是世界上最流行的语言之一,是一种运行在客户端的脚本语言 (Script 是脚本的意思) 脚本语言:不需要编译,运行过程中由 js 解释器( j ...

  3. 初始JavaScript,世界上最流行的语言之一!

    1.JavaScript 是什么? JavaScript 是世界上最流行的语言之一,是一种运行在客户端的脚本语言 (Script 是脚本的意思) 脚本语言:不需要编译,运行过程中由 js 解释器( j ...

  4. JavaScript 是世界上最好的语言?

    JavaScript 是世界上最好的语言 可能对于不同的来说世界上最好的语言可能非常vary,但是对于我来说,JavaScript就是我心目中那个最好的语言,由最开始只是出于响应式编程的toy lan ...

  5. 梅赛德斯-奔驰获得世界上第一个有条件自动驾驶的国际有效系统批准

    奔驰是世界上第一家满足UN-R157对3级系统苛刻法律要求的汽车公司. 奔驰是世界上第一家满足UN-R157对3级系统[1]的严格法律要求的汽车公司.德国联邦汽车运输管理局(KBA)已根据技术批准条例 ...

  6. JavaScript:世界上最被误解的语言

    JavaScript,或者叫 Mocha,或者叫 LiveScript,或者叫 JScript,又或者叫 ECMAScript,是世界上最流行的编程语言之一.事实上世界上的每一台个人电脑都安装并在频繁 ...

  7. JavaScript: 世界上最被误解的语言|Douglas Crockford

    这篇文章是javascript大牛Douglas Crockford 写的,实习的时候曾读过,现在再读,又有了不同的理解,特此转载. 原文地址:JavaScript: The Wrrrld's Mos ...

  8. Cortex—世界上第一个图形化人工智能界面问世

    文章来源:ATYUN AI平台 机器学习和AI很难理解,只有少数非常聪明的计算机科学家知道如何构建它们.但是一个新工具的设计者有一个很大的野心:为AI创建Javascript. 这个名为Cortex的 ...

  9. 世界上最强大的两个字母的单词

    Morpheus向Leo提供红色药丸和蓝色药丸-版权所有华纳兄弟公司. 这个词代表了指导宇宙和所有生命的因果定律. 这是一个很小的词,它本身不执行任何操作,但完全由其上下文定义. 没有两个单词比IF单 ...

最新文章

  1. html5网页仿写,纯CSS代码模仿绘制蚂蚁庄园页面
  2. 不用光盘可破解电脑系统密码
  3. java 强制安卓竖屏,Android4.0强制横屏竖屏
  4. 在deepin中安装docker
  5. 力扣559. N 叉树的最大深度(JavaScript)
  6. linux查看具体进程占用的网络流量
  7. C++ const和static const的区别
  8. 基于SSM的企业工资管理系统
  9. C#序列化出现“因其保护级别而不可访问。只能处理公共类型。”
  10. 机顶盒天线接头怎么接_户户通天线怎么安装图解
  11. 图的存储结构——邻接表
  12. java计算机毕业设计房屋租赁管理系统源码+系统+lw+数据库+调试运行
  13. 计算机专业专硕考研学校排名,计算机考研学校排名
  14. 阿里云国际版服务器如何搭建区块链应用程序
  15. win10关闭实时防护的步骤教程
  16. 基于 NIOS-II 软核的流水灯
  17. 正点原子STM32F103学习笔记(六)——时钟系统
  18. 加密算法之SHA(SHA1、SHA256)
  19. jsbarcode 条形码
  20. iOS开发之OC入门(类的基础知识)

热门文章

  1. 【今日CS 视觉论文速览】Mon, 14 Jan 2019
  2. 类与对象初识 类是模具 对象是产品 0314 2101
  3. 9203-1204-抄写
  4. 冒泡排序 实现数据的由大到小排序
  5. pptx版式验证代码
  6. 爬虫-urlparse与urlsplit
  7. linux 使用命令直接查看带单位的文件大小
  8. Mono SVN最新代码或者Mono 1.2.5 支持IronPython 2.0
  9. FPGA学习(第8节)-Verilog设计电路的时序要点及时序仿真
  10. 4位大佬解读:“医疗人工智能、信息化、政策与科研”的新风向与新趋势