Merge pull request #20923 from amwps290/2021-0203

translated
This commit is contained in:
Xingyu.Wang 2021-02-03 21:55:33 +08:00 committed by GitHub
commit 9437252540
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 291 additions and 300 deletions

View File

@ -1,300 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (amwps290)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Learn JavaScript by writing a guessing game)
[#]: via: (https://opensource.com/article/21/1/learn-javascript)
[#]: author: (Mandy Kendall https://opensource.com/users/mkendall)
Learn JavaScript by writing a guessing game
======
Take the first steps toward creating interactive, dynamic web content by
practicing some basic JavaScript concepts with a simple game.
![Javascript code close-up with neon graphic overlay][1]
It's pretty safe to say that most of the modern web would not exist without [JavaScript][2]. It's one of the three standard web technologies (along with HTML and CSS) and allows anyone to create much of the interactive, dynamic content we have come to expect in our experiences with the World Wide Web. From frameworks like [React][3] to data visualization libraries like [D3][4], it's hard to imagine the web without it.
There's a lot to learn, and a great way to begin learning this popular language is by writing a simple application to become familiar with some concepts. Recently, some Opensource.com correspondents have written about how to learn their favorite language by writing a simple guessing game, so that's a great place to start!
### Getting started
JavaScript comes in many flavors, but I'll start with the basic version, commonly called "Vanilla JavaScript." JavaScript is primarily a client-side scripting language, so it can run in any standard browser without installing anything. All you need is a code editor ([Brackets][5] is a great one to try) and the web browser of your choice.
### HTML user interface
JavaScript runs in a web browser and interacts with the other standard web technologies, HTML and CSS. To create this game, you'll first use HTML (Hypertext Markup Language) to create a simple interface for your players to use. In case you aren't familiar, HTML is a markup language used to provide structure to content on the web.
To start, create an HTML file for your code. The file should have the `.html` extension to let the browser know that it is an HTML document. You can call your file `guessingGame.html`.
Use a few basic HTML tags in this file to display the game's title, instructions for how to play, interactive elements for the player to use to enter and submit their guesses, and a placeholder for providing feedback to the player:
```
<!DOCTYPE>
  <[html][6]>
    <[head][7]>
      <[meta][8] charset="UTF-8" />
      <[title][9]> JavaScript Guessing Game </[title][9]>
    </[head][7]>
    <[body][10]>
      <[h1][11]>Guess the Number!</[h1][11]>
      <[p][12]>I am thinking of a number between 1 and 100. Can you guess what it is?</[p][12]>
   
      <[label][13] for="guess">My Guess</[label][13]>
      <[input][14] type="number" id="guess">
      <[input][14] type="submit" id="submitGuess" value="Check My Guess">
   
      <[p][12] id="feedback"></[p][12]>
    </[body][10]>
  </[html][6]>
```
The `<h1>` and `<p>` elements let the browser know what type of text to display on the page. The set of `<h1>` tags signifies that the text between those two tags (`Guess the Number!`) is a heading. The set of `<p>` tags that follow signify that the short block of text with the instructions is a paragraph. The empty set of `<p>` tags at the end of this code block serve as a placeholder for the feedback the game will give the player based on their guess.
### The &lt;script&gt; tag
There are many ways to include JavaScript in a web page, but for a short script like this one, you can use a set of `<script>` tags and write the JavaScript directly in the HTML file. Those `<script>` tags should go right before the closing `</body>` tag near the end of the HTML file.
Now, you can start to write your JavaScript between these two script tags. The final file looks like this:
```
&lt;!DOCTYPE&gt;
&lt;[html][6]&gt;
&lt;[head][7]&gt;
  &lt;[meta][8] charset="UTF-8" /&gt;
  &lt;[title][9]&gt; JavaScript Guessing Game &lt;/[title][9]&gt;
&lt;/[head][7]&gt;
&lt;[body][10]&gt;
  &lt;[h1][11]&gt;Guess the Number!&lt;/[h1][11]&gt;
  &lt;[p][12]&gt;I am thinking of a number between 1 and 100. Can you guess what it is?&lt;/[p][12]&gt;
  &lt;[form][15]&gt;
    &lt;[label][13] for="guess"&gt;My Guess&lt;/[label][13]&gt;
    &lt;[input][14] type="number" id="guess"&gt;
    &lt;[input][14] type="submit" id="submitGuess" value="Check My Guess"&gt;
  &lt;/[form][15]&gt;
  &lt;[p][12] id="feedback"&gt;&lt;/[p][12]&gt;
  &lt;[script][16]&gt;
    const randomNumber = Math.floor(Math.random() * 100) + 1
    console.log('Random Number', randomNumber)
    function checkGuess() {
      let myGuess = guess.value
      if (myGuess === randomNumber) {
        feedback.textContent = "You got it right!"
      } else if (myGuess &gt; randomNumber) {
        feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
      } else if (myGuess &lt; randomNumber) {
       feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
     }
   }
   submitGuess.addEventListener('click', checkGuess)
 &lt;/[script][16]&gt;
&lt;/[body][10]&gt;
&lt;/[html][6]&gt;
```
To run this in the browser, either double-click on the file or go to the menu in your favorite web browser and choose **File &gt; Open File**. (If you are using Brackets, you can also use the lightning-bolt symbol in the corner to open the file in the browser).
### Pseudo-random number generation
The first step in the guessing game is to generate a number for the player to guess. JavaScript includes several built-in global objects that help you write code. To generate your random number, use the Math object.
[Math][17] has properties and functions for working with mathematical concepts in JavaScript. You will use two Math functions to generate the random number for your player to guess.
Start with [Math.random()][18], which generates a pseudo-random number between 0 and 1. (Math.random is inclusive of 0 but exclusive of 1. This means that the function could generate a zero, but it will never generate a 1.)
For this game, set the random number between 1 and 100 to narrow down the player's options. Take the decimal you just generated and multiply it by 100 to produce a decimal between 0 and…not quite 100. But you'll take care of that in a few more steps.
Right now, your number is still a decimal, and you want it to be a whole number. For that, you can use another function that is part of the Math object, [Math.floor()][19]. Math.floor()'s purpose is to return the largest integer that is less than or equal to the number you give it as an argument—which means it rounds down to the nearest whole number:
```
`Math.floor(Math.random() * 100)`
```
That leaves you with a whole number between 0 and 99, which isn't quite the range you want. You can fix that with your last step, which is to add 1 to the result. Voila! Now you have a (somewhat) randomly generated number between 1 and 100:
```
`Math.floor(Math.random() * 100) + 1`
```
### Variables
Now you need to store the randomly generated number so that you can compare it to your player's guesses. To do that, you can assign it to a **variable**.
JavaScript has different types of variables you can choose, depending on how you want to use the variable. For this game, use const and let.
* **let** is used for variables if their value can change throughout the code.
* **const** is used for variables if their value should not be changed.
There's a little more to const and let, but this is all you need to know for now.
The random number is generated only once in the game, so you will use a const variable to hold the value. You want to give the variable a name that makes it clear what value is being stored, so name it `randomNumber`:
```
`const randomNumber`
```
_A note on naming: Variables and function names in JavaScript are written in camel case. If there is just one word, it is written in all lower case. If there is more than one word, the first word is all lower case, and any additional words start with a capital letter with no spaces between the words._
### Logging to the console
Normally, you don't want to show anyone the random number, but developers may want to know the number that was generated to use it to help debug the code. With JavaScript, you can use another built-in function, [console.log()][20], to output the number to the console in your browser.
Most browsers include Developer Tools that you can open by pressing the **F12** key on your keyboard. From there, you should see a tab labeled **Console**. Any information logged to the console will appear here. Since the code you have written so far will run as soon as the browser loads, if you look at the console, you should see the random number that you just generated! Hooray!
![Javascript game with console][21]
### Functions
Next, you need a way to get the player's guess from the number input field, compare it to the random number you just generated, and give the player feedback to let them know if they guessed correctly. To do that, write a function. A **function** is code that is grouped to perform a task. Functions are reusable, which means if you need to run the same code multiple times, you can call the function instead of rewriting all of the steps needed to perform the task.
Depending on the JavaScript version you are using, there are many different ways to write, or declare, a function. Since this is an introduction to the language, declare your function using the basic function syntax.
Start with the keyword `function` and then give the function a name. It's good practice to use a name that is an action that describes what the function does. In this case, you are checking the player's guess, so an appropriate name for this function would be `checkGuess`. After the function name, write a set of parentheses and then a set of curly braces. You will write the body of the function between these curly braces:
```
`function checkGuess() {}`
```
### Access the DOM
One of the purposes of JavaScript is to interact with HTML on a webpage. It does this through the Document Object Model (DOM), which is an object JavaScript uses to access and change the information on a web page. Right now, you need to get the player's guess from the number input field you set up in the HTML. You can do that using the `id` attribute you assigned to the HTML elements, which in this case is `guess`:
```
`<input type="number" id="guess">`
```
JavaScript can get the number the player enters into the number input field by accessing its value. You can do this by referring to the element's id and adding `.value` to the end. This time, use a `let` variable to hold the value of the user's guess:
```
`let myGuess = guess.value`
```
Whatever number the player enters into the number input field will be assigned to the `myGuess` variable in the `checkGuess` function.
### Conditional statements
The next step is to compare the player's guess with the random number the game generates. You also want to give the player feedback to let them know if their guess was too high, too low, or correct.
You can decide what feedback the player will receive by using a series of conditional statements. A **conditional statement** checks to see if a condition is met before running a code block. If the condition is not met, the code stops, moves on to check the next condition, or continues with the rest of the code without running the code in the conditional block:
```
if (myGuess === randomNumber){
  feedback.textContent = "You got it right!"
}
else if(myGuess &gt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
}
else if(myGuess &lt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
}
```
The first conditional block compares the player's guess to the random number the game generates using a comparison operator `===`. The comparison operator checks the value on the right, compares it to the value on the left, and returns the boolean `true` if they match and `false` if they don't.
If the number matches (yay!), make sure the player knows. To do this, manipulate the DOM by adding text to the `<p>` tag that has the id attribute "feedback." This works just like `guess.value` above, except instead of getting information from the DOM, it changes the information in it. `<p>` elements don't have a value like `<input>` elements—they have text instead, so use `.textContent` to access the element and set the text you want to display:
```
`feedback.textContent = "You got it right!"`
```
Of course, there is a good chance that the player didn't guess right on the first try, so if `myGuess` and `randomNumber` don't match, give the player a clue to help them narrow down their guesses. If the first conditional fails, the code will skip the code block in that `if` statement and check to see if the next condition is true. That brings you to your `else if` blocks:
```
else if(myGuess &gt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
}
```
If you were to read this as a sentence, it might be something like this: "If the player's guess is equal to the random number, let them know they got it right. Otherwise (else), check if the player's guess is greater than `randomNumber`, and if it is, display the player's guess and tell them it was too high."
The last possibility is that the player's guess was lower than the random number. To check that, add one more `else if` block:
```
else if(myGuess &lt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
}
```
### User events and event listeners
If you look at your script, you'll see that some of the code runs automatically when the page loads, but some of it does not. You want to generate the random number before the game is played, but you don't want to check the player's guess until they have entered it into the number input field and are ready to check it.
The code to generate the random number and log it to the console is outside of a function, so it will run automatically when the browser loads your script. However, for the code inside your function to run, you have to call it.
There are several ways to call a function. Here, you want the function to run when the player clicks on the "Check My Guess" button. Clicking a button creates a user event, which the JavaScript code can then "listen" for so that it knows when it needs to run a function.
The last line of code adds an event listener to the button to "listen" for when the button is clicked. When it "hears" that event, it will run the function assigned to the event listener:
```
`submitGuess.addEventListener('click', checkGuess)`
```
Just like the other instances where you access DOM elements, you can use the button's id to tell JavaScript which element to interact with. Then you can use the built-in `addEventListener` function to tell JavaScript what event to listen for.
You have already seen a function that takes parameters, but take a moment to look at how this works. Parameters are information that a function needs to perform its task. Not all functions need parameters, but the `addEventListener` function needs two. The first parameter it takes is the name of the user event for which it will listen. The user can interact with the DOM in many ways, like typing, moving the mouse, tabbing with the keyboard, or copying and pasting text. In this case, the user event you are listening for is a button click, so the first parameter will be `click`.
The second piece of information `addEventListener` needs is the name of the function to run when the user clicks the button. In this case, it's the `checkGuess` function.
Now, when the player presses the "Check My Guess" button, the `checkGuess` function will get the value they entered in the number input field, compare it to the random number, and display feedback in the browser to let the player know how they did. Awesome! Your game is ready to play.
### Learn JavaScript for fun and profit
This bit of Vanilla JavaScript is just a small taste of what this vast ecosystem has to offer. It's a language well worth investing time into learning, and I encourage you to continue to dig in and learn more.
--------------------------------------------------------------------------------
via: https://opensource.com/article/21/1/learn-javascript
作者:[Mandy Kendall][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/mkendall
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/code_javascript.jpg?itok=60evKmGl (Javascript code close-up with neon graphic overlay)
[2]: https://opensource.com/tags/javascript
[3]: https://opensource.com/article/20/11/reactjs-tutorial
[4]: https://opensource.com/article/18/9/open-source-javascript-chart-libraries
[5]: https://opensource.com/article/20/12/brackets
[6]: http://december.com/html/4/element/html.html
[7]: http://december.com/html/4/element/head.html
[8]: http://december.com/html/4/element/meta.html
[9]: http://december.com/html/4/element/title.html
[10]: http://december.com/html/4/element/body.html
[11]: http://december.com/html/4/element/h1.html
[12]: http://december.com/html/4/element/p.html
[13]: http://december.com/html/4/element/label.html
[14]: http://december.com/html/4/element/input.html
[15]: http://december.com/html/4/element/form.html
[16]: http://december.com/html/4/element/script.html
[17]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
[18]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
[19]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
[20]: https://developer.mozilla.org/en-US/docs/Web/API/Console/log
[21]: https://opensource.com/sites/default/files/javascript-game-with-console.png (Javascript game with console)

View File

@ -0,0 +1,291 @@
[#]: collector: "lujun9972"
[#]: translator: "amwps290"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
[#]: subject: "Learn JavaScript by writing a guessing game"
[#]: via: "https://opensource.com/article/21/1/learn-javascript"
[#]: author: "Mandy Kendall https://opensource.com/users/mkendall"
通过编写猜数游戏学习 JavaScript
======
通过使用一个简单的游戏来练习一些基本的 JavaScript 概念,迈出创建交互,动态 Web 内容的第一步。
![Javascript code close-up with neon graphic overlay][1]
可以肯定地说,没有 [JavaScript][2],大多数现代 web 都将不存在。 它是三种标准 Web 技术(以及 HTML 和 CSS )之一,它使任何人都可以创建许多交互式的动态内容,这是我们在使用万维网时所期望的。 从 [React][3] 这样的框架到 [D3][4] 这样的数据可视化库,很难想象没有它的网络。
现在有很多东西要学习,开始学习这种流行语言的好方法是编写一个简单的应用程序以熟悉某些概念。 最近Opensource.com 通讯员写了一篇关于如何通过编写简单的猜谜游戏来学习自己喜欢的语言的文章,因此这是一个很好的起点!
### 现在开始吧
JavaScript 有许多种风格,但我将从最基本的开始,通常称为 “ Vanilla JavaScript”。 JavaScript 主要是一种客户端脚本语言,因此它可以在任何标准浏览器中运行,而无需安装任何程序。 您只需要一个代码编辑器([Brackets ][5] 就是一个不错的选择)和一个 Web 浏览器。
### HTML 用户界面
JavaScript 在 Web 浏览器中运行,并与其他标准 Web 技术 HTML 和 CSS 交互。 要创建此游戏,您首先需要使用 HTML超文本标记语言来创建供玩家使用的简单界面。 如果您不熟悉HTML 是一种标记语言,用于为 Web 内容提供结构。
首先,先创建一个 HTML 文件。 该文件应具有`.html `扩展名,以使浏览器知道它是 HTML 文档。 您可以将文件命名为 `guessingGame.html`。
在此文件中使用一些基本的 HTML 标签来显示游戏的标题,玩法说明,供玩家用来输入和提交其猜测的交互式元素以及用于向玩家提供反馈的占位符:
```
&lt;!DOCTYPE&gt;
  &lt;[html][6]&gt;
    &lt;[head][7]&gt;
      &lt;[meta][8] charset="UTF-8" /&gt;
      &lt;[title][9]&gt; JavaScript Guessing Game &lt;/[title][9]&gt;
    &lt;/[head][7]&gt;
    &lt;[body][10]&gt;
      &lt;[h1][11]&gt;Guess the Number!&lt;/[h1][11]&gt;
      &lt;[p][12]&gt;I am thinking of a number between 1 and 100. Can you guess what it is?&lt;/[p][12]&gt;
   
      &lt;[label][13] for="guess"&gt;My Guess&lt;/[label][13]&gt;
      &lt;[input][14] type="number" id="guess"&gt;
      &lt;[input][14] type="submit" id="submitGuess" value="Check My Guess"&gt;
   
      &lt;[p][12] id="feedback"&gt;&lt;/[p][12]&gt;
    &lt;/[body][10]&gt;
  &lt;/[html][6]&gt;
```
&lt;h1&gt;&lt;p&gt; 元素使浏览器知道在页面上显示什么类型的文本。 标签对 `<h1></h1>` 表示标签(`Guess the Number!`)之间的文本是标题。 后面的一组`<p>` 标签表示带有说明的短文本是一个段落。 此代码块末尾的空 `<p>` 标签用作占位符,用于根据用户的输入提供一些反馈。
### &lt;script&gt; 标签
在网页中包含 JavaScript 的方法有很多种,但是对于像这样的简短脚本,可以使用一组 `<script>` 标签并将 JavaScript 直接写在 HTML 文件中。 这些 `<script>` 标签应位于 HTML 文件末尾附近的 `</body>` 标签之前。
现在,您可以开始在这两个脚本标签之间编写 JavaScript。 最终文件如下所示:
```javascript
&lt;!DOCTYPE&gt;
&lt;[html][6]&gt;
&lt;[head][7]&gt;
  &lt;[meta][8] charset="UTF-8" /&gt;
  &lt;[title][9]&gt; JavaScript Guessing Game &lt;/[title][9]&gt;
&lt;/[head][7]&gt;
&lt;[body][10]&gt;
  &lt;[h1][11]&gt;Guess the Number!&lt;/[h1][11]&gt;
  &lt;[p][12]&gt;I am thinking of a number between 1 and 100. Can you guess what it is?&lt;/[p][12]&gt;
  &lt;[form][15]&gt;
    &lt;[label][13] for="guess"&gt;My Guess&lt;/[label][13]&gt;
    &lt;[input][14] type="number" id="guess"&gt;
    &lt;[input][14] type="submit" id="submitGuess" value="Check My Guess"&gt;
  &lt;/[form][15]&gt;
  &lt;[p][12] id="feedback"&gt;&lt;/[p][12]&gt;
  &lt;[script][16]&gt;
    const randomNumber = Math.floor(Math.random() * 100) + 1
    console.log('Random Number', randomNumber)
    function checkGuess() {
      let myGuess = guess.value
      if (myGuess === randomNumber) {
        feedback.textContent = "You got it right!"
      } else if (myGuess &gt; randomNumber) {
        feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
      } else if (myGuess &lt; randomNumber) {
       feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
     }
   }
   submitGuess.addEventListener('click', checkGuess)
 &lt;/[script][16]&gt;
&lt;/[body][10]&gt;
&lt;/[html][6]&gt;
```
要在浏览器中运行此文件,请双击文件或打开您喜欢的浏览器,点击菜单,然后选择**文件->打开文件**。 (如果使用 Brackets 软件,也可以使用角落处的闪电图标在浏览器中打开文件)。
### 生成伪随机数
猜谜游戏的第一步是为玩家生成一个数字供玩家猜测。 JavaScript 包含几个内置的全局对象,可帮助您编写代码。 要生成随机数,请使用 Math 对象。
JavaScript中的 [Math][17] 具有处理和数学相关的属性和功能。 您将使用两个数学函数来生成随机数,供您的玩家猜测。
[Math.random()][18],会将生成一个介于 0 和 1 之间的伪随机数。( Math.random 包含 0 但不包含 1。这意味着该函数可以生成 0 ,永远不会产生 1.
对于此游戏,请将随机数设置在 1 到 100 之间以缩小玩家的选择范围。 取刚刚生成的小数,然后乘以 100以产生一个介于 0 到......甚至不是 100 之间的小数。至此,您将需要其他步骤来解决这个问题。
现在,您的数字仍然是小数,但您希望它是一个整数。 为此,您可以使用属于 Math 对象的另一个函数 [Math.floor()][19]。 Math.floor() 的目的是返回小于或等于您作为参数指定的数字的最大整数,这意味着它会四舍五入为最接近的整数:
```javascript
`Math.floor(Math.random() * 100)`
```
这样您将得到 0 到 99 之间的整数,这不是您想要的范围。 您可以在最后一步修复该问题,即在结果中加 1。 瞧! 现在,您有一个(有点)随机生成的数字,介于 1 到 100 之间:
```javascript
`Math.floor(Math.random() * 100) + 1`
```
### 变量
现在,您需要存储随机生成的数字,以便可以将其与玩家的猜测进行比较。 为此,您可以将其存储到一个 **变量**
JavaScript 具有不同类型的变量,您可以选择这些类型,具体取决于您要如何使用该变量。 对于此游戏,请使用 const 和 let 。
* **let** 用于指示变量在整个程序中可以改变
* **const** 用于指示变量不应该被修改.
const 和 let 还有很多要说的,但现在知道这些就足够了。
随机数在游戏中仅生成一次,因此您将使用 const 变量来保存该值。 您想给变量起一个清楚地表明要存储什么值的名称,因此将其命名为 `randomNumber`
```javascript
`const randomNumber`
```
有关命名的注意事项JavaScript 中的变量和函数名称以驼峰形式编写。 如果只有一个单词,则全部以小写形式书写。 如果有多个单词,则第一个单词均为小写,其他任何单词均以大写字母开头,且单词之间没有空格。
### 打印到控制台
通常,您不想向任何人显示随机数,但是开发人员可能想知道生成的数字以使用它来帮助调试代码。 使用 JavaScript您可以使用另一个内置函数 [console.log()][20] 将数字输出到浏览器的控制台。
大多数浏览器都包含开发人员工具,您可以通过按键盘上的 **F12** 键来打开它们。 从那里,您应该看到一个标签为 **控制台** 的标签。 打印到控制台的所有信息都将显示在此处。 由于到目前为止编写的代码将在浏览器加载后立即运行,因此,如果您查看控制台,您应该会看到刚刚生成的随机数! 万岁!
![Javascript game with console][21]
### 函数
接下来,您需要一种方法来从数字输入字段中获得玩家的猜测,将其与您刚刚生成的随机数进行比较,并向玩家提供反馈,让他们知道他们是否正确猜到了。 为此,编写一个函数。 **函数** 是执行一定任务的代码块。 函数是可以重用的,这意味着如果您需要多次运行相同的代码,则可以调用函数,而不必重写执行任务所需的所有步骤。
根据您使用的 JavaScript 版本,有许多不同的方法来编写或声明函数。 由于这是该语言的基础入门,因此请使用基本函数语法声明函数。
以关键字 `function` 开头,然后起一个函数名。 好的做法是使用一个描述该函数的功能的名称。 在这个例子中,您正在检查玩家的猜测的数,因此此函数的名字可以是 `checkGuess`。 在函数名称之后,写上一组括号,然后写上一组花括号。 您将在以下花括号之间编写函数的主体:
```
`function checkGuess() {}`
```
### 使用 DOM
JavaScript 的目的之一是与网页上的 HTML 交互。 它通过文档对象模型DOM进行此操作DOM 是 JavaScript 用于访问和更改网页信息的对象。 现在,您需要从 HTML 中获取数字输入字段中玩家的猜测。 您可以使用分配给 HTML 元素的 `id` 属性(在这种情况下为 `guess`)来做到这一点:
```
`<input type="number" id="guess">`
```
JavaScript 可以通过访问玩家输入到数字输入字段中的数来获取其值。 您可以通过引用元素的 ID 并在末尾添加 `.value` 来实现。 这次,使用 `let` 定义的变量来保存用户的猜测值:
```
`let myGuess = guess.value`
```
玩家在数字输入字段中输入的任何数字都将被分配给 `checkGuess` 函数中的 `myGuess` 变量。
### 条件语句
下一步是将玩家的猜测与游戏产生的随机数进行比较。 您还想给玩家反馈,让他们知道他们的猜测是太高,太低还是正确。
您可以使用一系列条件语句来决定玩家将收到的反馈。 **条件语句** 在运行代码块之前检查是否满足条件。 如果不满足条件,则代码停止,继续检查下一个条件,或者继续执行其余代码,而无需执行条件块中的代码:
```
if (myGuess === randomNumber){
  feedback.textContent = "You got it right!"
}
else if(myGuess &gt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
}
else if(myGuess &lt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
}
```
第一个条件块使用比较运算符 `===` 将玩家的猜测与游戏生成的随机数进行比较。 比较运算符检查右侧的值,将其与左侧的值进行比较,如果匹配则返回布尔值 `true` ,否则返回布尔值 `false`
如果数字匹配(猜对了!),为了让玩家知道。 通过将文本添加到具有 id 属性 "feedback" 的 `<p>` 标记中来操作 DOM。 就像上面的 `guess.value` 一样工作,除了不是从 DOM 获取信息,而是更改其中的信息。 `<p>` 元素没有像 `<input>` 元素那样的值,而是具有文本,因此请使用 `.textContent` 访问元素并设置要显示的文本:
```
`feedback.textContent = "You got it right!"`
```
当然,玩家很有可能在第一次尝试时就猜错了,因此,如果 `myGuess``randomNumber` 不匹配,请给玩家一个线索,以帮助他们缩小猜测范围。 如果第一个条件失败,则代码将跳过该 if 语句中的代码块,并检查下一个条件是否为 true。 这使您进入 `else if` 块:
```
else if(myGuess &gt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
}
```
如果您将其作为句子阅读,则可能是这样的:“如果玩家的猜测等于随机数,请让他们知道他们猜对了。否则,请检查玩家的猜测是否大于 `randomNumber`,如果是,则显示玩家的猜测并告诉他们太高了。”
最后一种可能性是玩家的猜测低于随机数。 要检查这一点,再添加一个 `else if` 块:
```
else if(myGuess &lt; randomNumber) {
  feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
}
```
### 用户事件和事件监听器
如果您看上面的代码,则会看到某些代码在页面加载时自动运行,但有些则不会。 您想在玩游戏之前生成随机数,但是您不想在玩家将数字输入到数字输入字段并准备检查它之前检查其猜测。
生成随机数并将其打印到控制台的代码不在函数的范围内,因此它将在浏览器加载脚本时自动运行。 但是,要使函数内部的代码运行,您必须对其进行调用。
调用函数有几种方法。 在此,您希望该函数在用户单击“检查我的猜测”按钮时运行。 单击按钮将创建一个用户事件,然后 JavaScript 可以 “监听” 这个事件,以便知道何时需要运行函数。
代码的最后一行将事件侦听器添加到按钮上,以在单击按钮时调用函数。 当它“听到”该事件时,它将运行分配给事件侦听器的函数:
```
`submitGuess.addEventListener('click', checkGuess)`
```
就像访问 DOM 元素的其他实例一样,您可以使用按钮的 ID 告诉 JavaScript 与哪个元素进行交互。 然后,您可以使用内置的 `addEventListener` 函数来告诉 JavaScript 要监听的事件。
您已经看到了带有参数的函数,但花点时间看一下它是如何工作的。 参数是函数执行其任务所需的信息。 并非所有函数都需要参数,但是 `addEventListener` 函数需要两个参数。 它采用的第一个参数是将为其侦听的用户事件的名称。 用户可以通过多种方式与 DOM 交互,例如键入,移动鼠标,键盘上的 TAB 键和粘贴文本。 在这种情况下,您正在监听的用户事件是单击按钮,因此第一个参数将是 ` click`
`addEventListener`的第二个所需的信息是用户单击按钮时要运行的函数的名称。 这里我们需要 `checkGuess` 函数。
现在,当玩家按下“检查我的猜测”按钮时,`checkGuess` 函数将获得他们在数字输入字段中输入的值,将其与随机数进行比较,并在浏览器中显示反馈,以使玩家知道他们猜的怎么样。 太棒了! 您的游戏已准备就绪。
### 学习 JavaScript 以获取乐趣和收益
一点点的 Vanilla JavaScript 只是这个庞大的生态系统所提供功能的一小部分。 这是一种值得花时间投入学习的语言,我鼓励您继续挖掘并学习更多。
--------------------------------------------------------------------------------
via: https://opensource.com/article/21/1/learn-javascript
作者:[Mandy Kendall][a]
选题:[lujun9972][b]
译者:[amwps290](https://github.com/amwps290)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/mkendall
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/code_javascript.jpg?itok=60evKmGl "Javascript code close-up with neon graphic overlay"
[2]: https://opensource.com/tags/javascript
[3]: https://opensource.com/article/20/11/reactjs-tutorial
[4]: https://opensource.com/article/18/9/open-source-javascript-chart-libraries
[5]: https://opensource.com/article/20/12/brackets
[6]: http://december.com/html/4/element/html.html
[7]: http://december.com/html/4/element/head.html
[8]: http://december.com/html/4/element/meta.html
[9]: http://december.com/html/4/element/title.html
[10]: http://december.com/html/4/element/body.html
[11]: http://december.com/html/4/element/h1.html
[12]: http://december.com/html/4/element/p.html
[13]: http://december.com/html/4/element/label.html
[14]: http://december.com/html/4/element/input.html
[15]: http://december.com/html/4/element/form.html
[16]: http://december.com/html/4/element/script.html
[17]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
[18]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
[19]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
[20]: https://developer.mozilla.org/en-US/docs/Web/API/Console/log
[21]: https://opensource.com/sites/default/files/javascript-game-with-console.png "Javascript game with console"