pull/580/merge
zhuoliuzhou 9 months ago committed by GitHub
commit 54ab091233
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,667 @@
| 第#天 | 内容 |
| :---- | :--------------------------------------------------------------------------------: |
| 01 | [引入 Introduction](./readMe.md) |
| 02 | [数据类型 Data Types](./第二天_数据类型/第二天_数据类型.md) |
| 03 | [布尔值、操作符、日期 Booleans, Operators, Date](./第三天_布尔值_运算符_日期/第三天_布尔值_运算符_日期.md) |
| 04 | 条件结构 Conditionals |
| 05 | 列表 Arrays |
| 06 | 循环结构 Loops |
| 07 | 函数 Functions |
| 08 | 对象 Objects |
| 09 | 高级函数 Higher Order Functions |
| 10 | 集合与映射 Sets and Maps |
| 11 | 解构与展开 Destructuring and Spreading |
| 12 | 正则表达式 Regular Expressions |
| 13 | 控制台对象方法 Console Object Methods |
| 14 | 错误处理 Error Handling |
| 15 | 类 Classes |
| 16 | JSON |
| 17 | 网络内容存储 Web Storages |
| 18 | 承诺函数 Promises |
| 19 | 闭包 Closure |
| 20 | 撰写清晰的代码 Writing Clean Code |
| 21 | 文档对象模型 DOM |
| 22 | 操作DOM对象 Manipulating DOM Object |
| 23 | 事件监听器 Event Listeners |
| 24 | 迷你项目:太阳系 Mini Project: Solar System |
| 25 | 迷你项目世界各国家数据可视化1 Mini Project: World Countries Data Visualization 1 |
| 26 | 迷你项目世界各国家数据可视化1 Mini Project: World Countries Data Visualization 2 |
| 27 | 迷你项目:项目集 Mini Project: Portfolio |
| 28 | 迷你项目:排行榜 Mini Project: Leaderboard |
| 29 | 迷你项目:动画字符 Mini Project: Animating characters |
| 30 | 毕业项目 Final Projects |
🧡🧡🧡 HAPPY CODING 🧡🧡🧡
<div>
<small>请支持 <strong>作者</strong> 创造更多教学材料</small> <br />
<a href = "https://www.paypal.me/asabeneh"><img src='https://1000logos.net/wp-content/uploads/2021/04/Paypal-logo.png' alt='Paypal Logo' style="width:10%"/></a>
</div>
<div align="center">
<h1> 30天入门JavaScript引入</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>作者:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> 1月, 2020</small>
</sub>
<div>
🇬🇧 [English](../readMe.md)
🇨🇳 [中文 Chinese](./readMe.md)
</div>
</div>
[第二天 >>](./第二天_数据类型/第二天_数据类型.md)
![Thirty Days Of JavaScript](../images/day_1_1.png)
- [📔 第一天](#-第一天)
- [引入](#引入)
- [在开始路程前,你需要具备](#在开始路程前你需要具备)
- [准备工作](#准备工作)
- [安装 Node.js](#安装-nodejs)
- [浏览器](#浏览器)
- [安装谷歌Chrome](#安装谷歌chrome)
- [开启Chrome控制台](#开启chrome控制台)
- [在控制台写代码](#在控制台写代码)
- [Console.log方法](#consolelog方法)
- [Console.log 支持多个输入参数](#consolelog-支持多个输入参数)
- [注释](#注释)
- [语法](#语法)
- [算术](#算术)
- [代码编辑器](#代码编辑器)
- [安装Visual Studio Code](#安装visual-studio-code)
- [如何使用 Visual Studio Code](#如何使用-visual-studio-code)
- [将 JavaScript 添加到网页](#将-javascript-添加到网页)
- [文内代码 Inline Script](#文内代码-inline-script)
- [内部代码 Internal Script](#内部代码-internal-script)
- [外部代码 External Script](#外部代码-external-script)
- [多个外部代码 Multiple External Scripts](#多个外部代码-multiple-external-scripts)
- [数据类型](#数据类型)
- [数值 Numbers](#数值-numbers)
- [字符串 Strings](#字符串-strings)
- [布尔值 Booleans](#布尔值-booleans)
- [未定义值 Undefined](#未定义值-undefined)
- [空 Null](#空-null)
- [检查数据类型](#检查数据类型)
- [注释,再次介绍](#注释再次介绍)
- [变量](#变量)
- [💻 第一天: 作业](#-第一天-作业)
# 📔 第一天
## 引入
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**恭喜你** 决定踏上30天入门Javascript的旅途。在这30天里你将会学到成为JS程序员或者更广泛一些编程的必备知识。最终你将获得30天入门JavaScript 证书。若你需要其他帮助或想帮助其他人,请加入[TG群](https://t.me/ThirtyDaysOfJavaScript).
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**30天入门Javascript** 挑战适合初学者和进阶开发人员。欢迎来到JavaScript的世界。 JavaScript是互联网的语言。我在使用和教学JavaScript的过程中感受到了生命的大和谐也希望你可以和我一同和谐。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;本教程将循序渐进带你学习人类历史上最受欢迎的语言之一 - JavaScript。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JavaScript一般应用场景包括 **_为网页添加交互功能、开发移动应用、桌面应用、游戏等 _** ,现在甚至可应用于 **_机器学习_****_人工智能_**. **_JavaScript (JS)_** 的人气在近几年不断上升且已经连续六年成为排头编程语言而且是github上使用最多的语言之一。
## 在开始路程前,你需要具备
其实本课程不要求任何编程知识,你只需要有:
1. 主观能动性
2. 一台电脑
3. 村里连上网
4. 浏览器
5. 代码编辑器
## 准备工作
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;相信你已经有充足的主观能动性和意愿成为一个程序开发商,另外,你也已经有电脑和连上网了。具备这些软硬件,就可以出发了!
### 安装 Node.js
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;虽然现在还用不上Node.js但之后也会需要所以先装了没毛病 -> [node.js](https://nodejs.org/en/).
![Node download](../images/download_node.png)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;下载安装包并安装
![Install node](../images/install_node.png)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;安装完毕后,可以调出控制台检查是否安装成功。
```sh
asabeneh $ node -v
v12.14.0
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在编制本教程时我使用的Node版本是12.14.0, 不过推荐版本是v14.17.6, 在你观看本教程时相信已经有更新的版本了。
### 浏览器
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;浏览器有很多选择但我强烈推荐谷歌Chrome。
#### 安装谷歌Chrome
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;若你目前没有Chrome可按此安装[Google Chrome](https://www.google.com/chrome/) 。我们可以在浏览器控制台写一些小型的JavaScript代码不过不会使用控制台来开发应用。
![Google Chrome](../images/google_chrome.png)
#### 开启Chrome控制台
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;可以通过点按右上角的三个点的按钮,选择 _更多工具 -> 开发者工具_ 或快捷键,我更推荐快捷键。
![Opening chrome](../images/opening_developer_tool.png)
快捷键:
```sh
Mac
Command+Option+J
Windows/Linux:
Ctl+Shift+J
```
![Opening console](../images/opening_chrome_console_shortcut.png)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;开启控制台后我们来探索一下里面的元素。之后我们大部分学习将围绕控制台展开这里是JavsScript代码运行的地方。谷歌控制台V8引擎将你的JavaScript代码转换为机器语言。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;接下来我们开始在控制台里写一些JavaScript代码
![write code on console](../images/js_code_on_chrome_console.png)
#### 在控制台写代码
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;我们可以在谷歌(或其他浏览器)的控制台里写任意代码。不过在本教程里我们主要是用谷歌控制台。首先,用快捷键开启控制台
```sh
Mac
Command+Option+I
Windows:
Ctl+Shift+I
```
##### Console.log方法
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第一行代码将用到一个JavaScript内建函数 **console.log()**。我们输入一串字符作为这个函数的参数,函数将会在控制台展示我们输入的字符。比如 `'Hello, World'`
```js
console.log('Hello, World!')
```
##### Console.log 支持多个输入参数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**`console.log()`** 函数可以接收多个参数,用逗号分隔。语法: **`console.log(参数1, 参数2, 参数3)`**
![console log multiple arguments](../images/console_log_multipl_arguments.png)
```js
console.log('Hello', 'World', '!')
console.log('HAPPY', 'NEW', 'YEAR', 2020)
console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript')
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;从上面截图可以看到, _`console.log()`_ 可以接受多个参数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;恭喜你成功写出了第一句使用_`console.log()`_函数的JavaScript代码!
##### 注释
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;我们可以为我们的代码添加注释。注释可以另我们的代码更好理解。JavaScript会略过注释内容。在JavaScript中在语句的最开头输入 // 以代表其后的语句为注释。
**例1单行注释**
```js
// 这是第一个注释
// 这是第二个注释
// 这是单行注释
```
**例2多行注释**
```js
/*
这是多行注释,
顾名思义,可以包含多行文字,
JavaScrpt是互联网的语言
*/
```
##### 语法
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;编程语言和人类语言很类似。英语或其他语言通过字词句段篇章等来传达信息。“语法”的意思是 _语言中通过排列文字、词语、短语以创造结构化的句子。_ 而编程世界中“语法”代表计算机语言的结构。每个编程语言都有自己的语法。JavaScript也不例外。如果我们编写的语法JavaScript理解不了那么就会产生各种各样的错误。我们会在之后的课程中学习各种常见的错误。现在我们先学习什么是“语法错误 (symtax error)” 。
![Error](../images/raising_syntax_error.png)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在此我特意制造了一个错误,控制台抛出了错误提示。可以看到,错误提示已经非常清晰地提示了我们犯了哪一类错误。根据错误反馈指引,我们可以修改代码改正错误。这个过程又叫做纠错(debugging)。让我来解决这个错误:
```js
console.log('Hello, World!')
console.log('Hello, World!')
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;现在,我们已经知道如何使用 _`console.log()`_. 来展示字符。如果我们希望 _`console.log()`_ 输出我们需要的结果,那么输入的参数必须用单引号、双引号或反引号(`)框住。
**例:**
```js
console.log('Hello, World!')
console.log("Hello, World!")
console.log(`Hello, World!`)
```
#### 算术
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 现在,让我们尝试用数字类型作为 _`console.log()`_ 的参数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 除了文字我们可以用JavaScript作数学运算让我们先试试一些简单的计算。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在浏览器的控制台中其实不需要使用 **_`console.log()`_** 函数就可以输出结果。不过我们在这里统一使用,因为之后大部分的教程需要在文字编辑器里写代码,必须通过 **_`console.log()`_** 函数来输出结果。
![Arithmetic](../images/arithmetic.png)
```js
console.log(2 + 3) // Addition
console.log(3 - 2) // Subtraction
console.log(2 * 3) // Multiplication
console.log(3 / 2) // Division
console.log(3 % 2) // Modulus - finding remainder
console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3
```
### 代码编辑器
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 我们可以在控制台里直接写代码但是这种做法不利于建立大型项目。在真实场景中开发人员一般用各种代码编辑器来写代码。在本教程里我们会使用Visual Studio Code来写代码。
#### 安装Visual Studio Code
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Visual Studio Code 是一个非常流行的开源代码编辑器。我一般都推荐使用 [Visual Studio Code](https://code.visualstudio.com/), 当然,如果你已经习惯使用别的编辑器也可以。
![Vscode](../images/vscode.png)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 安装好Visual Studio Code后我们继续课程。
#### 如何使用 Visual Studio Code
双击开启 Visual Studio Code你会看到如下界面可按下图操作。
![Vscode ui](../images/vscode_ui.png)
![Vscode add project](../images/adding_project_to_vscode.png)
![Vscode open project](../images/opening_project_on_vscode.png)
![script file](../images/scripts_on_vscode.png)
![Installing Live Server](../images/vsc_live_server.png)
![running script](../images/running_script.png)
![coding running](../images/launched_on_new_tab.png)
## 将 JavaScript 添加到网页
在网页中添加 JavaScript 有三种方式:
- **_文内代码 Inline script_**
- **_内部代码 Internal script_**
- **_外部代码 External script_**
- **_多个外部代码 Multiple External scripts_**
我们将会演示每一种方法。
### 文内代码 Inline Script
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在电脑桌面或其他路径创建一个项目文档命名为“30DaysOfJS”并在文档哪创建一个名为 **_`index.html`_** 的文件。然后将以下代码复制粘贴到文件内,并用浏览器打开,例如[Chrome](https://www.google.com/chrome/).
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfScript:Inline Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!')">Click Me</button>
</body>
</html>
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 现在你已经写了人生第一句文内代码这段代码用JavaScript内建的_`alert()`_函数生成了一个对话框并显示一段文字。
### 内部代码 Internal Script
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 内部代码可以写在HTML文档的 _`head`_ 块或 _`body`_但一般推荐是摆在body块。现在让我们先试试在head块中编写代码
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
<script>
console.log('Welcome to 30DaysOfJavaScript')
</script>
</head>
<body></body>
</html>
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 下方则是常见的内部代码编写模式即在HTML的body块内编写代码。用浏览器打开该文件可以在控制台看到 `console.log()`的输出结果。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
<script>
console.log('Welcome to 30DaysOfJavaScript')
</script>
</body>
</html>
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Open the browser console to see the output from the `console.log()`.
![js code from vscode](../images/js_code_vscode.png)
### 外部代码 External Script
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 与内部代码类似外部代码可以摆在header或body块但是建议摆在body。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 首先我们在project文件夹中建立一个外部的 JavaScript 文件(.js后缀命名为“introduction.js“。复制粘贴以下代码到文件中并保存并在HTML的body块中链接此.js文件。
```js
console.log('Welcome to 30DaysOfJavaScript')
```
_head_ 中插入外部代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script>
</head>
<body></body>
</html>
```
_body_ 中插入外部代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!-- JavaScript external link could be in the header or in the body -->
<!-- Before the closing tag of the body is the recommended place to put the external JavaScript script -->
<script src="introduction.js"></script>
</body>
</html>
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 开启浏览器控制台查看 `console.log()`的输出结果。
### 多个外部代码 Multiple External Scripts
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在HTML文件中可以同时链接多个JavaScript文件。例如在项目文件夹内创建一个新的.js文件命名为“`helloworld.js`”并写入以下代码:
```js
console.log('Hello, World!')
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multiple External Scripts</title>
</head>
<body>
<script src="./helloworld.js"></script>
<script src="./introduction.js"></script>
</body>
</html>
```
_最重要的.js文件需要摆在所有其他代码文件签名这点非常重要。_
![Multiple Script](../images/multiple_script.png)
## 数据类型
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; JavaScript和其他编程语言一样支持多种数据类型。JavaScript 的原始数据类型包括: _String, Number, Boolean, undefined, Null_, and _Symbol_.
### 数值 Numbers
- 证书 Integers: 整型负整数、0、正整数数值
例:
... -3, -2, -1, 0, 1, 2, 3 ...
- 浮点数值 Float-point numbers: 小数
例:
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
### 字符串 Strings
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 一个或多个字符的集合,需用单引号、双引号或反引号框住。
**例:**
```js
'a'
'Asabeneh'
"Asabeneh"
'Finland'
'JavaScript是美妙的编程语言'
'I love teaching'
'I hope you are enjoying the first day'
`We can also create a string using a backtick`
'A string could be just as small as one character or as big as many pages'
'Any data type under a single quote, double quote or backtick is a string'
```
### 布尔值 Booleans
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 布尔值的取值范围只有两个数true 或 false. 所有对比操作都会返回布尔值。
**例:**
```js
true // if the light is on, the value is true
false // if the light is off, the value is false
```
### 未定义值 Undefined
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在 JavaScript 中,如果我们没有给一个变量赋值,那么这个变量的值就是“未定义值”。另外,如果一个函数没有任何返回值,那么默认返回“未定义值”
```js
let firstName
console.log(firstName) // undefined, because it is not assigned to a value yet
```
### 空 Null
“空” Null 代表空白值
```js
let emptyValue = null
```
## 检查数据类型
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 通过 **typeof** 操作符可以检查数据类型,比如以下例子:
```js
console.log(typeof 'Asabeneh') // 字符串 string
console.log(typeof 5) // 数值 number
console.log(typeof true) // 布尔值 boolean
console.log(typeof null) // 对象类型 object type
console.log(typeof undefined) // 未定义值 undefined
```
## 注释,再次介绍
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; JavaScript里的注释也和其他编程语言一样主要服务于代码的可读性。
有两种注释类型:
- _单行注释_
- _多行注释_
单行注释:
```js
// commenting the code itself with a single comment
// let firstName = 'Asabeneh'; single line comment
// let lastName = 'Yetayeh'; single line comment
```
多行注释:
```js
/*
let location = 'Helsinki';
let age = 100;
let isMarried = true;
This is a Multiple line comment
*/
```
## 变量
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 变量是数据的_容器_数据通过变量_存储_在内存中。当声明一个变量时一部分内存被留存。当该变量被赋值时这部分内存就相应填充所赋的值。JavaScript用 _var__let__const_ 关键字来声明变量。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_let_ 来声明取值可变的变量,用 _const_ 来声明去值不会变的变量比如PI国家名字、重力加速度等。在此教程中我们不会使用 var因为我不建议使用这个关键词。这个关键词很容易产生各种错误。在别的章节会详细介绍var和const。
JavaScript 变量需要遵循以下规则:
- 首字符不能是数字。
- 除了下划线和美元符号,不可以使用其他特殊符号。
- 骆驼型字符命名例如aJavaScriptVariable
- 不能有空格。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 以下是合规范的变量名。
```js
firstName
lastName
country
city
capitalCity
age
isMarried
first_name
last_name
is_married
capital_city
num1
num_1
_num_1
$num1
year2020
year_2020
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例子中的头两个变量就是骆驼型变量名的形式。在此教程中,我们会采用首字母小写骆驼型命名变量,用首字母大写骆驼型命名类。
不合规的变量名例子:
```js
first-name
1_num
num_#_1
```
接着,我们可以用各种数据类型声明变量。语法是 _let__const_ 关键字 + 变量名 = 数值
```js
// Syntax
let nameOfVariable = value
```
nameOfVriable 是一个变量他的值是value
**例:声明变量**
```js
// 声明不同数据类型的变量 Declaring different variables of different data types
let firstName = 'Asabeneh' // first name of a person
let lastName = 'Yetayeh' // last name of a person
let country = 'Finland' // country
let city = 'Helsinki' // capital city
let age = 100 // age in years
let isMarried = true
console.log(firstName, lastName, country, city, age, isMarried)
```
```sh
Asabeneh Yetayeh Finland Helsinki 100 true
```
```js
// Declaring variables with number values
let age = 100 // age in years
const gravity = 9.81 // earth gravity in m/s2
const boilingPoint = 100 // water boiling point, temperature in °C
const PI = 3.14 // geometrical constant
console.log(gravity, boilingPoint, PI)
```
```sh
9.81 100 3.14
```
```js
// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble
let name = 'Asabeneh', job = 'teacher', live = 'Finland'
console.log(name, job, live)
```
```sh
Asabeneh teacher Finland
```
当你用浏览器打开 _index.html_ 时,你会看见:
![Day one](../images/day_1.png)
🌕 你真牛逼!你已经完成了第一天的挑战,并朝牛逼头子更进一步。现在让我们来做一些轻松愉快的作业吧~
# 💻 第一天: 作业
1. 写一句单行注释内容为_comments can make code readable_。Write a single line comment which says, _comments can make code readable_
2. 写一句单行注释内容为_Welcome to 30DaysOfJavaScript_。Write another single comment which says, _Welcome to 30DaysOfJavaScript_
3. 写一段多行注释,内容为 _comments can make code readable, easy to reuse_
_and informative_。Write a multiline comment which says, _comments can make code readable, easy to reuse_
_and informative_
4. 创建一个名为 variable.js 的文件并声明类型为字符串、布尔值、未定义值及空值的变量。Create a variable.js file and declare variables and assign string, boolean, undefined and null data types
5. 创建一个名为 datatypes.js 的文件,并使用 **_typeof_** 操作符来检查每一个变量的数据类型。Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable
6. 声明一个变量不要赋值。Declare four variables without assigning values
7. 声明一个变量并赋值。Declare four variables with assigned values
8. 用多行代码声明多个变量来存储你的姓、名、婚姻状况、国际、年龄。Declare variables to store your first name, last name, marital status, country and age in multiple lines
9. 用**一**行代码声明多个变量来存储你的姓、名、婚姻状况、国际、年龄。Declare variables to store your first name, last name, marital status, country and age in a single line
10. 声明两个变量 _myAge__yourAge_ 并赋值在浏览器控制台输出以下结果。Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console.
```sh
I am 25 years old.
You are 30 years old.
```
🎉 恭喜!🎉
[第二天 >>](./第二天_数据类型/第二天_数据类型.md)

@ -0,0 +1,625 @@
<div align="center">
<h1> 30天入门JavaScript布尔值、运算符、日期</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>作者:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> 1月, 2020</small>
</sub>
</div>
[<< 第二天](../第二天_数据类型/第二天_数据类型.md) | [第四天 >>](../04_Day_Conditionals/04_day_conditionals.md)
![Thirty Days Of JavaScript](/images/banners/day_1_3.png)
- [📔 第三天](#-第三天)
- [布尔值](#布尔值)
- [程序识别为true的值](#程序识别为true的值)
- [程序识别为False的值](#程序识别为false的值)
- [未定义值](#未定义值)
- [Null](#null)
- [运算符](#运算符)
- [赋值运算符(=](#赋值运算符)
- [算术运算符](#算术运算符)
- [比较操作符](#比较操作符)
- [逻辑运算符](#逻辑运算符)
- [增值运算符](#增值运算符)
- [减值运算符](#减值运算符)
- [条件运算符](#条件运算符)
- [运算符优先次序](#运算符优先次序)
- [视窗函数Window Method](#视窗函数window-method)
- [视窗 alert() 函数](#视窗-alert-函数)
- [视窗 prompt() 函数](#视窗-prompt-函数)
- [视窗 confirm() 函数](#视窗-confirm-函数)
- [日期对象](#日期对象)
- [建立 time 对象](#建立-time-对象)
- [获取完整的年份](#获取完整的年份)
- [获取月份](#获取月份)
- [获取日期](#获取日期)
- [获取星期日期](#获取星期日期)
- [获取小时数](#获取小时数)
- [获取分钟数](#获取分钟数)
- [获取秒数](#获取秒数)
- [获取时间](#获取时间)
- [💻 第三天:作业](#-第三天作业)
- [作业:难度水平 1](#作业难度水平-1)
- [作业:难度水平 2](#作业难度水平-2)
- [作业:难度水平 3](#作业难度水平-3)
# 📔 第三天
## 布尔值
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 布尔数据类型只有两个值_true_ 和 _false_。这种数据类型最常运用于比较中。所有比较都会返回布尔值,即 true 或 false。
**例:布尔值**
```js
let isLightOn = true
let isRaining = false
let isHungry = false
let isMarried = true
let truValue = 4 > 3 // true
let falseValue = 4 < 3 // false
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 再次强调布尔数据类型只有两个值true 和 false。
### 程序识别为true的值
- 所有数字正或负都是true除了0
- 所有字符串都是true除了空字符串
- 布尔值true。
### 程序识别为False的值
- 0
- 0nBigInt 型变量)
- 空值null
- 未定义值undefined
- 非数字NaN
- 布尔值False
- '', "", ``, 空白字符
熟记这些程序识别为true或false的值很有用在之后的章节中我们会在条件结构中利用这个性质做决策。
## 未定义值
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果我们声明一个变量但不赋值,那么这个变量的类型就是未定义值。另外,如果一个函数没有返回任何值(即没有 return 语句那么这个函数的返回值默认是未定义值。注意函数本身是function类型
```js
let firstName
console.log(firstName) //未定义值,因为还未赋值
```
## Null
```js
let empty = null
console.log(empty) // -> 空值,表示一片虚无
```
## 运算符
### 赋值运算符(=
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 等号(=)就是赋值运算符,用来给变量赋值。
```js
let firstName = 'Asabeneh'
let country = 'Finland'
```
赋值运算符列表
![Assignment operators](/images/assignment_operators.png)
### 算术运算符
算术运算符用于数学计算
- 加(+): a + b
- 减(-): a - b
- 乘(*): a * b
- 除(/): a / b
- 求余(%): a % b
- 指数(**): a ** b
```js
let numOne = 4
let numTwo = 3
let sum = numOne + numTwo
let diff = numOne - numTwo
let mult = numOne * numTwo
let div = numOne / numTwo
let remainder = numOne % numTwo
let powerOf = numOne ** numTwo
console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64
```
```js
const PI = 3.14
let radius = 100 // 半径
//计算圆的周长
const areaOfCircle = PI * radius * radius
console.log(areaOfCircle) // 314 m
const gravity = 9.81 // in m/s2
let mass = 72 // in Kilogram
// 计算物体质量
const weight = mass * gravity
console.log(weight) // 706.32 N(Newton)
const boilingPoint = 100 // 常温下水的沸点(摄氏度)
const bodyTemp = 37 // 常温下体温(摄氏度)
// 用字符串模版编辑字符串
/*
The boiling point of water is 100 oC.
Human body temperature is 37 oC.
The gravity of earth is 9.81 m/s2.
*/
console.log(
`The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${bodyTemp} oC.\nThe gravity of earth is ${gravity} m / s2.`
)
```
### 比较操作符
在程序中我们经常需要比较两个值的大小,这需要用到比较操作符。
![Comparison Operators](/images/comparison_operators.png)
**例:比较操作符**
```js
console.log(3 > 2) // true, 因为3大于2
console.log(3 >= 2) // true, 因为3大于2
console.log(3 < 2) // false, 32
console.log(2 < 3) // true, 23
console.log(2 <= 3) // true, 因为2小于3
console.log(3 == 2) // false, 因为3大于2
console.log(3 != 2) // true, 因为3大于2
console.log(3 == '3') // true, 仅比较值
console.log(3 === '3') // false, 比较值和数据类型
console.log(3 !== '3') // true, 比较值和数据类型
console.log(3 != 3) // false, 仅比较值
console.log(3 !== 3) // false, 比较值和数据类型
console.log(0 == false) // true, 相等
console.log(0 === false) // false, 数据类型不同
console.log(0 == '') // true, 相同
console.log(0 == ' ') // true, 相同
console.log(0 === '') // false, 数据类型不同
console.log(1 == true) // true, 相同
console.log(1 === true) // false, 数据类型不同
console.log(undefined == null) // true
console.log(undefined === null) // false
console.log(NaN == NaN) // false, 定义上不等
console.log(NaN === NaN) // false
console.log(typeof NaN) // number
console.log('mango'.length == 'avocado'.length) // false
console.log('mango'.length != 'avocado'.length) // true
console.log('mango'.length < 'avocado'.length) // true
console.log('milk'.length == 'meat'.length) // true
console.log('milk'.length != 'meat'.length) // false
console.log('tomato'.length == 'potato'.length) // true
console.log('python'.length > 'dragon'.length) // false
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 理解上面的语句需要一些理解,单纯靠背而不理解背后逻辑的话很难应用。
JavaScript 其实是一个有些怪的程序语言,偶尔会给你和你预想不一致的结果。<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 总而言之,如果 == 返回了 false那么 === 一定会返回 false。用 === 相对来说更加安全(避免一些奇怪的意想不到的错误)。这个[链接](https://dorey.github.io/JavaScript-Equality-Table/)列出了所有JavaScript的数据类型比较。
### 逻辑运算符
常用逻辑运算符:&&(与) , ||(或) and !(非).
- &&仅当两个比较值均是true值时返回true
- ||当两个比较值有至少一个是true值时返回true
- !取相反值true = false。
```js
// && 例子
const check = 4 > 3 && 10 > 5 // true && true -> true
const check = 4 > 3 && 10 < 5 // true && false -> false
const check = 4 < 3 && 10 < 5 // false && false -> false
// || 例子
const check = 4 > 3 || 10 > 5 // true || true -> true
const check = 4 > 3 || 10 < 5 // true || false -> true
const check = 4 < 3 || 10 < 5 // false || false -> false
//! 例子
let check = 4 > 3 // true
let check = !(4 > 3) // false
let isLightOn = true
let isLightOff = !isLightOn // false
let isMarried = !false // true
```
### 增值运算符
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;用增值运算符来增加一个变量储存的值可以理解为运算和赋值的结合。增值运算符分为前增值Pre-increment和后增值Post-increment具体区别
1. 前增值
```js
let count = 0
console.log(++count) // 1
console.log(count) // 1
```
2. 后增值
```js
let count = 0
console.log(count++) // 0
console.log(count) // 1
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;一般最常用的是后增值,所以至少需要学会使用后增值即可。
### 减值运算符
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;和增值类似是用来减少变量的存储值分为前减值Pre-decrement和后减值Post-decrement
1. 前减值
```js
let count = 0
console.log(--count) // -1
console.log(count) // -1
```
2. 后减值
```js
let count = 0
console.log(count--) // 0
console.log(count) // -1
```
### 条件运算符
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 条件运算符用来写一个简易的条件结构,请看下例:
```js
let isRaining = true
isRaining
? console.log('You need a rain coat.')
: console.log('No need for a rain coat.')
isRaining = false
isRaining
? console.log('You need a rain coat.')
: console.log('No need for a rain coat.')
```
```sh
You need a rain coat.
No need for a rain coat.
```
```js
let number = 5
number > 0
? console.log(`${number} is a positive number`)
: console.log(`${number} is a negative number`)
number = -5
number > 0
? console.log(`${number} is a positive number`)
: console.log(`${number} is a negative number`)
```
```sh
5 is a positive number
-5 is a negative number
```
### 运算符优先次序
我建议在这个[官方文档链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)查看运算符优先次序。
## 视窗函数Window Method
### 视窗 alert() 函数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在之前的章节中,我们用 alert() 函数制造了一个弹窗,里面包含了一些文字和一个 OK 按钮。这是一个内建函数,作用是在弹窗内显示输入的参数。
```js
alert(message)
```
```js
alert('Welcome to 30DaysOfJavaScript')
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;但建议不要经常使用这个函数,因为弹窗很烦人,建议只在测试环节用这个函数。
### 视窗 prompt() 函数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; prompt 函数会显示一个弹窗内容包含一个输入框输入的内容可以保存在变量中。prompt() 函数接受两个变量,其中第二个变量代表默认输入值,可选择不填。
```js
prompt('required text', 'optional text')
```
```js
let number = prompt('Enter number', 'number goes here')
console.log(number)
```
### 视窗 confirm() 函数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; confirm() 函数展示一个对话框、一些文字、一个 OK 按钮和一个 Cancel 按钮。确认对话框通常用来向用户获取许可来执行某些操作。confirm() 函数可以接收字符串作为参数。
点击 OK 按钮将返回 true点击 cancel 按钮将返回 false。
```js
const agree = confirm('Are you sure you like to delete? ')
console.log(agree) // 结果是true或是false取决于你在对话框里的选择
```
这些只是视窗函数的一部分,我们会在之后的章节更深入学习视窗函数。
## 日期对象
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;时间是很重要的,我们经常需要知道一个行为或事件发生的具体时间。
JavaScript 通过 Date 对象建立日期和时间变量。Date对象提供了许多函数供我们处理日期和时间。<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;用来获取日期或时间信息的函数通常以 _get_ 开头例如_getFullYear(), getMonth(), getDate(),
getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_ 等等。
![Date time Object](/images/date_time_object.png)
### 建立 time 对象
time 对象提供关于时间的信息。
```js
const now = new Date()
console.log(now) // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time)
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 当我们创建了 time 对象后,我们可以用前面提到的 get 函数获取日期/时间信息。
### 获取完整的年份
```js
const now = new Date()
console.log(now.getFullYear()) // 2020
```
### 获取月份
```js
const now = new Date()
console.log(now.getMonth()) // 0, because the month is January, month(0-11)
```
### 获取日期
```js
const now = new Date()
console.log(now.getDate()) // 4, because the day of the month is 4th, day(1-31)
```
### 获取星期日期
```js
const now = new Date()
console.log(now.getDay()) // 6, because the day is Saturday which is the 7th day
// Sunday is 0, Monday is 1 and Saturday is 6
// Getting the weekday as a number (0-6)
```
### 获取小时数
```js
const now = new Date()
console.log(now.getHours()) // 0, because the time is 00:56:41
```
### 获取分钟数
```js
const now = new Date()
console.log(now.getMinutes()) // 56, because the time is 00:56:41
```
### 获取秒数
```js
const now = new Date()
console.log(now.getSeconds()) // 41, because the time is 00:56:41
```
### 获取时间
以下两种方法可获取自1970年1月1日Unix time到目前时刻的毫秒数。
1. Using _getTime()_
```js
const now = new Date() //
console.log(now.getTime()) // 1578092201341, 自1970年1月1日到目前时刻2020年1月4日 00:56:41的毫秒数。
```
2. Using _Date.now()_
```js
const allSeconds = Date.now() //
console.log(allSeconds) // 1578092201341, 自1970年1月1日到目前时刻2020年1月4日 00:56:41的毫秒数
const timeInSeconds = new Date().getTime()
console.log(allSeconds == timeInSeconds) // true
```
让我们来将这些值转换为方便识别的格式,
**例:**
```js
const now = new Date()
const year = now.getFullYear() // return year
const month = now.getMonth() + 1 // return month(0 - 11)
const date = now.getDate() // return date (1 - 31)
const hours = now.getHours() // return number (0 - 23)
const minutes = now.getMinutes() // return number (0 -59)
console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
```
🌕 你有无尽的能量!你刚刚完成了第三天的挑战,朝着牛逼侠已经迈出了三大步。现在又到了熟悉的快乐作业时间。
## 💻 第三天:作业
### 作业:难度水平 1
1. 声明变量,命名为 firstName, lastName, country, city, age, isMarried, year 并赋值,用 typeof 运算符检视每一个变量的数据类型;
2. 检查 '10' 的数据类型是否等于 10
3. 检查 parseInt('9.8') 是否等于 10
4. 布尔值只有true和false两个取值
1. 写出三个返回true的JavaScript语句
2. 写出三个返回false的JavaScript语句
5. 在大脑中计算以下表达式的返回值,再用 console.log() 验证:
1. 4 > 3
2. 4 >= 3
3. 4 < 3
4. 4 <= 3
5. 4 == 4
6. 4 === 4
7. 4 != 4
8. 4 !== 4
9. 4 != '4'
10. 4 == '4'
11. 4 === '4'
12. 返回“python”和“jargon”的字符串长度并编写一个返回false的语句。
6. 在大脑中计算以下表达式的返回值,再用 console.log() 验证:
1. 4 > 3 && 10 < 12
2. 4 > 3 && 10 > 12
3. 4 > 3 || 10 < 12
4. 4 > 3 || 10 > 12
5. !(4 > 3)
6. !(4 < 3)
7. !(false)
8. !(4 > 3 && 10 < 12)
9. !(4 > 3 && 10 > 12)
10. !(4 === '4')
11. “on” 既不存在于 “dragon” 也不存在于 “python”
7. 使用Date对象回答以下问题
1. 今天的年份是?
2. 今天的月份用数字表示是?
3. 今天的日期是?
4. 今天的日期用数字表示是?
5. 现在是几点?
6. 现在是几分?
7. 现在距离1970年1月1日过去了多少秒
### 作业:难度水平 2
1. 编写一段代码:弹出对话框让用户输入三角形的底和高,计算面积并返回。 (面积 = 0.5 x 底 x 高).
```sh
输入 底: 20
输入 高: 10
这个三角形的面积是: 100
```
2. 编写一段代码:弹出对话框让用户输入三角形的三条边,计算周长并返回。 (周长 = 边1 + 边2 + 边3)
```sh
输入 边1: 5
输入 边2: 4
输入 边3: 3
这个三角形的周长是: 12
```
3. 用对话框输入长和宽,计算长方形面积和周长。
4. 用对话框输入半径,计算圆的面积和周长。(面积 = pi x 半径 x 半径, 周长 = 2 x pi x 半径pi = 3.14)。
5. 计算线段 y = 2x -2 的斜率、与x轴的交点和与y轴的交点。
6. 斜率计算公式是 m = (y<sub>2</sub>-y<sub>1</sub>)/(x<sub>2</sub>-x<sub>1</sub>). 计算两个点 (2, 2)(6,10) 之间线段的斜率。
7. 对比5和6的两个斜率。
8. 根据方程 (y = x<sup>2</sup> + 6x + 9). 用不同的x计算y的值并找到使 y = 0 的x值。
9. 编写一段代码:弹出对话框让用户输入小时和时薪,计算收入:
```sh
输入 小时数: 40
输入 时薪: 28
你的每周收入为: 1120
```
10. 如果你的名字的长度大于7个字符返回“你的名字好长啊否则返回“你的名字好短啊”。
11. 对比你的名和姓的长度(拼音),并输出以下:
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
```
```sh
你的名儿 Asabeneh 比你的姓儿 Yetayeh 长。
```
12. 声明两个变量 _myAge__yourAge_ 按以下赋值,并输出结果:
```js
let myAge = 250
let yourAge = 25
```
```sh
老子比你大225岁
```
13. 用对话框获取用户的出身年份如果用户超过17岁则允许用户开车否则提示用户需要等几年。
```sh
输入 出身年份1995
你今年25岁可以开车了
输入 出身年份2005
你才15岁. 还需要再过3年才能开车
```
14. 编写一段代码弹出对话框让用户输入年数转换成秒数。比如假设某人活了100岁输出以下
```sh
输入 你活了多少岁100
你已经度过了 3153600000 秒
```
15. 用以下格式显示当前日期:
1. YYYY-MM-DD HH:mm
2. DD-MM-YYYY HH:mm
3. DD/MM/YYYY HH:mm
### 作业:难度水平 3
1. 用 Date time对象创建一个可读的时间格式其中小时数和分钟数必须占两位例如7小时5分钟显示07:05
1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05
[<< 第二天](../第二天_数据类型/第二天_数据类型.md) | [第四天 >>](../04_Day_Conditionals/04_day_conditionals.md)

@ -0,0 +1,975 @@
<div align="center">
<h1> 30 Days Of JavaScript: Data Types</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>作者:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> 1月, 2020</small>
</sub>
</div>
</div>
[<< 第一天](../readMe.md) | [第三天 >>](../第三天_布尔值_运算符_日期/第三天_布尔值_运算符_日期.md)
![Thirty Days Of JavaScript](/images/banners/day_1_2.png)
- [📔 第二天](#-第二天)
- [数据类型](#数据类型)
- [原始数据类型](#原始数据类型)
- [非原始数据类型](#非原始数据类型)
- [数值Numbers](#数值numbers)
- [声明数值变量](#声明数值变量)
- [Math 对象](#math-对象)
- [随机数生成器](#随机数生成器)
- [字符串Strings](#字符串strings)
- [合并字符串](#合并字符串)
- [用加号(+)合并字符串](#用加号合并字符串)
- [长字符串](#长字符串)
- [分离字符Escape Sequences](#分离字符escape-sequences)
- [模版字符串](#模版字符串)
- [字符串方法](#字符串方法)
- [检查数据类型和类型转换](#检查数据类型和类型转换)
- [检查数据类型](#检查数据类型)
- [转换数据类型Casting](#转换数据类型casting)
- [字符串 -> 整数](#字符串---整数)
- [字符串 -> 小数](#字符串---小数)
- [小数 -> 整数](#小数---整数)
- [💻 第二天:作业](#-第二天作业)
- [作业:难度水平 1](#作业难度水平-1)
- [作业:难度水平 2](#作业难度水平-2)
- [作业:难度水平 3](#作业难度水平-3)
# 📔 第二天
## 数据类型
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在前一章节,我们粗略地提到了数据类型。每一个数据和值都有它们对应的数据类型,数据类型代表了数据的特征。数据类型大致可以分为两类:
1. 原始数据类型 primitive data type
2. 非原始数据类型对象引用Non-primitive data types 或 Object References
### 原始数据类型
JavaScript中的原始数据类型包括:
1. 数值Numbers- 整数,浮点小数;
2. 字符串Strings- 任何被单引号、双引号或反引号框住的内容;
3. 布尔值Booleans- true 或 false
4. 空值Null- 空白 或 无;
5. 未定义值Undefined- 已声明但未赋值的变量
6. 符号Symbol- 一种独特的值,可通过符号构造函数生成;
非原始数据类型包括:
1. 对象Objects
2. 列表Arrays
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;那么,到底什么是原始数据类型,什么是非原始数据类型吧。
*原始* 数据类型是不可变(无法修改)的数据类型。当某个原始数据类型被创建,我们无法修改它。
**例:**
```js
let word = 'JavaScript'
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;如果我们尝试修改这个变量 *word* 所储存的字符串JavaScript会报错。再次说明任何被单引号、双引号或反引号框住的内容都是字符串类型数值。
```js
word[0] = 'Y'
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;尝试运行上面的语句不会改变 *word* 变量存储的字符串。所以,我们说字符串数据型是不可变的。<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;当对原始数据类型进行比较时实际上是在对比他们的值value。下面的例子我们尝试对比不同的数据值:
```js
let numOne = 3
let numTwo = 3
console.log(numOne == numTwo) // true
let js = 'JavaScript'
let py = 'Python'
console.log(js == py) //false
let lightOn = true
let lightOff = false
console.log(lightOn == lightOff) // false
```
### 非原始数据类型
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *非原始* 数据类型是可变的可修改。我们可以在创建非原始数据类型变量后修改它的值。下例中我们创建了一个列表。列表是用方括号框住的一列数据。列表可以包含相同或不同的数据类型。列表的值可通过对应的序号获取。JavaScript规定列表的序号从0开始也就是说一个列表的第一个值的序号是0第二个值的序号是1依此类推。
```js
let nums = [1, 2, 3]
nums[0] = 10
console.log(nums) // [10, 2, 3]
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 由上可见,列表是可变的。非原始数据类型不能进行对比。即便两个非原始数据类型的变量具有相同的性质和值,它们严格意义上也是不相等的。
```js
let nums = [1, 2, 3]
let numbers = [1, 2, 3]
console.log(nums == numbers) // false
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
console.log(userOne == userTwo) // false
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 所以,务必牢记,不要对比非原始数据类型的变量,包括列表、函数或对象。<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 非原始数据类型变量的“值”的类型是引用类型reference type因为当对它们进行比较时实际上比较的是所引用的地址而不是值。若两个对象引用的是同一个底层对象那么它们才是严格意义上的相等。
```js
let nums = [1, 2, 3]
let numbers = nums
console.log(nums == numbers) // true
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = userOne
console.log(userOne == userTwo) // true
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果你还是不太理解原始数据类型和非原始数据类型的区别别担心先继续学习。等之后再回头来看这部分也许会有不一样的体会。现在让我们首先细聊一下数值类型Number
## 数值Numbers
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 数值包括整数和小数,可以进行算术运算,让我们看几个例子。
### 声明数值变量
```js
let age = 35
const gravity = 9.81 // 用const定义不会改变值的变量
let mass = 72 // 质量kg
const PI = 3.14 // PI 也是固定值用const定义
// 更多例子
const boilingPoint = 100 // 水的常温下沸点(摄氏温度)也是固定值。
const bodyTemp = 37 // 常温下人体平均摄氏温度,固定值。
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp)
```
### Math 对象
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; JavaScript内建的 Math 对象包含了很多实用的方法可以运用于数值类型变量。
```js
const PI = Math.PI
console.log(PI) // 3.141592653589793
// 四舍五入
console.log(Math.round(PI)) // PI 四舍五入得到 3
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3向下取整
console.log(Math.ceil(PI)) // 4向上取整
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5返回最小值
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20返回最大值
const randNum = Math.random() // 产生介于 0 0.999999 的随机数
console.log(randNum)
// 产生介于 0 10 的随机数
const num = Math.floor(Math.random () * 11) // 产生介于 0 10 的随机数
console.log(num)
//绝对值
console.log(Math.abs(-10)) // 10
//平方根
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
//次方
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
//对数
//通过函数返回自然对数以e为底数参数x为指数
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
//通过 Math 对象内建常量返回自然对数,
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
//三角函数
Math.sin(0)
Math.sin(60)
Math.cos(0)
Math.cos(60)
```
#### 随机数生成器
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; JavaScript 的 Math 对象提供的 random() 函数可以产生介于 0 0.999999... 的随机数。
```js
let randomNum = Math.random() // g介于 0 0.999999... 的随机数
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 现在,我们尝试用 random() 函数产生介于0 10 之间的随机数。
```js
let randomNum = Math.random() // 介于 0 0.999999... 的随机数
let numBtnZeroAndTen = randomNum * 11
console.log(numBtnZeroAndTen) // 返回值范围: 0 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)
console.log(randomNumRoundToFloor) // 返回值范围:- 10
```
## 字符串Strings
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 字符串是一串文字,并用 **_单引号_****_双引号_** 或 **_反引号_** 框住。声明一个字符串变量时,我们需要定义变量名,声明操作符(=),以及一串用单引号、双引号或反引号框住的值。下面给你们打几个样儿;
```js
let space = ' ' // 空格键
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let quote = "俗话说得好‘一日之计在于晨’"
let quotWithBackTick = `有道是'车到山前必有路‘`
```
### 合并字符串
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 将两个或以上字符串相连叫做合并。我们用之前定义的字符串来演示:
```js
let fullName = firstName + space + lastName; // 合并三个字符串
console.log(fullName);
```
```sh
Asabeneh Yetayeh
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 我们可以用多种方式合并字符串。
#### 用加号(+)合并字符串
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 用加号合并字符串是old school容易导致错误。在此介绍这种方法供参考但是我强烈建议使用 ES6 标准模版字符串(之后详解)。
```js
// 定义不同类型的变量
let space = ' '
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName =firstName + space + lastName
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5 string addition
console.log(personInfoOne)
```
```sh
Asabeneh Yetayeh. I am 250. I live in Finland
```
#### 长字符串
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;字符串可以是一个字母、一段话甚至一页内容。如果字符串太长导致一行无法容纳,我们可以用斜线(\\)来标记行末,代表字符串将在下一行继续。
**例:**
```js
const paragraph = "My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\
I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \
Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \
In the end of 2019, I was thinking to expand my teaching and to reach \
to global audience and I started a Python challenge from November 20 - December 19.\
It was one of the most rewarding and inspiring experience.\
Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \
I hope you are enjoying too."
console.log(paragraph)
```
#### 分离字符Escape Sequences
JavaScript 和大部分其他编程语言使用 \ + 一些字符作为分离字符,让我们看一些常用的分离字符:
- \n: 换行字符
- \t: Tab字符代表8个空格
- \\\\: 斜线
- \\': 单引号
- \\": 双引号
```js
console.log('I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // 换行
console.log('Days\tTopics\tExercises')
console.log('Day 1\t3\t5')
console.log('Day 2\t3\t5')
console.log('Day 3\t3\t5')
console.log('Day 4\t3\t5')
console.log('This is a backslash symbol (\\)') // 在字符串中显示斜线
console.log('In every programming language it starts with \"Hello, World!\"')
console.log("In every programming language it starts with \'Hello, World!\'")
console.log('The saying \'Seeing is Believing\' isn\'t correct in 2020')
```
控制台输出如下:
```sh
I hope everyone is enjoying the 30 Days Of JavaScript challenge.
Do you ?
Days Topics Exercises
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
In every programming language it starts with 'Hello, World!'
The saying 'Seeing is Believing' isn't correct in 2020
```
#### 模版字符串
模版字符串用反引号框住。在模版字符串中我们可以使用表达式。表达式用花括号框住,前面需要加一个美元符号$。语法如下:
```js
//Syntax
`String literal text`
`String literal text ${expression}`
```
**例1**
```js
console.log(`The sum of 2 and 3 is 5`) // statically writing the data
let a = 2
let b = 3
console.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data dynamically
```
**例2**
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName = firstName + ' ' + lastName
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`
console.log(personInfoTwo)
console.log(personInfoThree)
```
```sh
I am Asabeneh Yetayeh. I am 250. I live in Finland.
I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 用模版字符串,我们可以加入表达式。表达式可以是一个值,或者是语句(对比、运算或条件运算符)。
```js
let a = 2
let b = 3
console.log(`${a} is greater than ${b}: ${a > b}`)
```
```sh
2 is greater than 3: false
```
### 字符串方法
在 JavaScript 里,所有东西都是对象。字符串是原始数据类型,在定义之后就不能修改。字符串对象内建了很多实用方法可以用来处理字符串变量。
1. *length*:字符串的 *length* 方法返回该字符串的字符长度,包括空格字符。
**例:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8
```
2. *获取字符串内的字符*我们可以用序号获取字符串里面的每一个字符。类似列表字符串的序号也是从0开始最后一个字符的序号是字符串的长度减1.
![Accessing sting by index](/images/string_indexes.png)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 让我们尝试获取 'JavaScript' 这个字符串里的字符吧:
```js
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
3. *toUpperCase()*: 这个方法将字符串转换为大写。
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: 这个方法将字符串转换为小写。
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland
```
5. *substr()*:这个方法获取字符串的子字符串,需要两个参数:开始序号和子字符串长度。
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: 这个方法也是获取字符串的子字符串,需要两个参数:开始序号和结束序号。注意,返回的子字符串不包括结束序号的字符。
```js
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land
```
7. *split()*:此方法将字符串按参数分隔
```js
let string = '30 Days Of JavaScript'
console.log(string.split()) // Changes to an array -> ["30 Days Of JavaScript"]
console.log(string.split(' ')) // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // Change to an array - > ["Asabeneh"]
console.log(firstName.split('')) // Split to an array at each letter -> ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*:删除字符串首尾的空白字符。
```js
let string = ' 30 Days Of JavaScript '
console.log(string)
console.log(string.trim(' '))
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim()) // still removes spaces at the beginning and the end of the string
```
```sh
30 Days Of JavasCript
30 Days Of JavasCript
Asabeneh
Asabeneh
```
9. *includes()*此方法通过输入一个子字符串查询是否包含在目标字符串中。若包含则返回true。
```js
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false - it is case sensitive!
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
console.log(string.includes('Java')) // true
let country = 'Finland'
console.log(country.includes('fin')) // false
console.log(country.includes('Fin')) // true
console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false
```
10. *replace()*:替换函数,需要两个参数,旧字符串和替换字符串。
```js
string.replace(oldsubstring, newsubstring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*:输入序号返回对应的字符
```js
string.charAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)) // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t
```
12. *charCodeAt()*输入序号返回对应字符的字符编码ASCII编码
```js
string.charCodeAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII number is 68
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116
```
13. *indexOf()*:输入子字符串,返回该子字符串的首字符在目标字符串的位置。若目标字符串不包含子字符串,返回-1。
```js
string.indexOf(substring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
```
14. *lastIndexOf()*:输入子字符串,返回该子字符串的最后一个字符在目标字符串的位置。若目标字符串不包含子字符串,返回-1。
```js
//syntax
string.lastIndexOf(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*:可以输入多个字符串,返回合并后的字符串。
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*:输入字符串,检查目标字符串的开头是否和输入字符串一致,返回布尔值。
```js
//syntax
string.startsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
let country = 'Finland'
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
```
17. *endsWith*:输入字符串,检查目标字符串的结尾是否和输入字符串一致,返回布尔值。
```js
string.endsWith(substring)
```
```js
let string = 'Love is the most powerful feeling in the world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in the world')) // true
let country = 'Finland'
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
```
18. *search*:输入字符串或正则表达式,返回目标字符串中第一个符合输入字符串的序号。
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
19. *match*:输入字符串或正则表达式,若目标字符串匹配到输入字符串,则返回列表,否则返回空值。在此我们顺便看看正则表达式,它是用斜线框住的字符串+标记。
```js
let string = 'love'
let patternOne = /love/ // 没有标记
let patternTwo = /love/gi // g代表搜索整个texti代表无视大小写
```
Match syntax
```js
// syntax
string.match(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))
```
```sh
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 让我们用正则表达式从字符串中获取数字。别担心,这只是一个简单的例子,并不是对正则表达式的全部介绍,之后的章节会有详细说明。
```js
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge'
let regEx = /\d+/
// 斜线后加d是分离字符代表匹配的是数字而不是字母d
// + 号代表一个或以上数字
// 若斜线后有g标记则代表搜索全文。
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*输入数字n返回重复n次字段并合并。
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## 检查数据类型和类型转换
### 检查数据类型
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_typeof_ 方法检查数据类型。
**Example:**
```js
// 不同的数据类型
// 让我们先定义不同的数据类型变量
let firstName = 'Asabeneh' // 字符串
let lastName = 'Yetayeh' // 字符串
let country = 'Finland' // 字符串
let city = 'Helsinki' // 字符串
let age = 250 // 数值
let job // 未定义值,因为还未赋值
console.log(typeof 'Asabeneh') // 字符串
console.log(typeof firstName) // 字符串
console.log(typeof 10) // 数值
console.log(typeof 3.14) // 数值
console.log(typeof true) // 布尔值
console.log(typeof false) // 布尔值
console.log(typeof NaN) // 数值
console.log(typeof job) // 未定义值
console.log(typeof undifined) // 未定义值
console.log(typeof null) // 对象
```
### 转换数据类型Casting
- 转换Casting将一种数据类型转换为另一种数据类型。常用的方法包括 _parseInt()__parseFloat()__Number()__+ 号_ 或 _str()_
当我们对字符串形式的数字进行运算时,需要先将其转换为数值类型再进行运算,否则会报错。
#### 字符串 -> 整数
可以将字符串形式的数字转换为数字。字符串型数字就是引号内的数字,例如:'10', '5'。
可用以下方法将字符串型数字转换为整数:
- parseInt() 函数
- Number() 函数
- 加号(+)
```js
let num = '10'
let numInt = parseInt(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = Number(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = +num
console.log(numInt) // 10
```
#### 字符串 -> 小数
同样地,我们也可以将字符串型数字转换为小数。字符串形式的小数形如:'9.81', '3.14', '1.44'。
可用以下方法把字符串型数字转换为小数:
- parseFloat() 函数
- Number() 函数
- 加号(+)
```js
let num = '9.81'
let numFloat = parseFloat(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = Number(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = +num
console.log(numFloat) // 9.81
```
#### 小数 -> 整数
可以通过以下方法将小数转换为整数。
- parseInt() 函数
```js
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
```
🌕 你可太牛逼了!就在此刻,你完成了第二天的挑战,你已经向牛逼头子迈出坚实的两大步了!现在,让我们做一些轻松愉快的小作业巩固知识吧~
## 💻 第二天:作业
### 作业:难度水平 1
1. 定义变量命名为“challenge”并赋值 **'30 Days Of JavaScript'**。
2. 用 __console.log()__ 将1中变量输出到浏览器控制台。
3. 用 _console.log()_ 输出1中变量的 __字符串长度__ 到浏览器控制台。
4. 用 __toUpperCase()__ 函数将1中变量转换为全大写。
5. 用 __toLowerCase()__ 函数将1中变量转换为全小写。
6. 用 __substr()____substring()__ 获取1中变量的第一个词。
7. 将 *Days Of JavaScript* 字符串从 *30 Days Of JavaScript* 字符串中剥离。
8. 用 __includes()__ 函数检查1中变量是否包含词语 __Script__
9. 用 __split()__ 函数将1中变量分隔成 __列表__ 。
10. 用 __split()__ 函数将字符串 ”30 Days Of JavaScript“ 按空格分隔成列表。
11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' 按逗号 __分隔__ 此字符串形成列表。
12. 用 __replace()__ 函数将字符串 ”30 Days Of JavaScript“ 修改为 ”30 Days Of Python“。
13. ”30 Days Of JavaScript“ 这个字符串的序号为15的字符是什么请使用 __charAt()__ 函数。
14. ”30 Days Of JavaScript“ 这个字符串里字符”J“的字符编码是什么请使用 __charCodeAt()__ 函数。
15. 用 __indexOf__ 函数找到 __a__ 字符在”30 Days Of JavaScript“字符串中第一次出现的位置。
16. 用 __lastIndexOf__ 函数找到 __a__ 字符在”30 Days Of JavaScript“字符串中最后一次出现的位置。
17. 用 __indexOf__ 函数找到 __because__ 这个词在 __”You cannot end a sentence with because because because is a conjunction“__ 这个句子中第一次出现的位置。
18. 用 __lastIndexOf__ 函数找到 __because__ 这个词在 __"You cannot end a sentence with because because because is a conjunction"__ 这个句子中第最后出现的位置。
19. 用 __search__ 函数找到 __because__ 这个词在 __”You cannot end a sentence with because because because is a conjunction“__ 这个句子中第一次出现的位置。
20. 用 __trim()__ 函数删除' 30 Days Of JavaScript '字符串的前后空格.
21. 将 __startsWith()__ 函数运用于 *30 Days Of JavaScript* 字符串并返回true
22. 用 __endsWith()__ 函数运用于 *30 Days Of JavaScript* 字符串并返回true
23. 用 __match()__ 函数找到 *30 Days Of JavaScript* 字符串里所有字母 __a__
24. 用 __concat()__ 函数合并 '30 Days of' 和 'JavaScript' 得到 '30 Days Of JavaScript'。
25. 用 __repeat()__ 函数输出两次*30 Days Of JavaScript* 。
### 作业:难度水平 2
1. 用 console.log() 输出以下字符串
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
2. 用 console.log() 输出特蕾莎修女的名言:
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
3. 检查 typeof '10' 是否等于 10。如果不是使其相等。
4. 检查 parseFloat('9.8') 是否等于 10。如果不是使其相等。
5. 检查是否可以在 “python”和“jargon”中找到“on“。
6. _I hope this course is not full of jargon_. 检查 _jargon_ 是否在前句中。
7. 产生一个 \[0,100\] 的随机数。
8. 产生一个 \[50,100\] 的随机数。
9. 产生一个 \[0,255\] 的随机数。
10. 用随机数获取 'JavaScript' 字符串中的一个字符。
11. 用 console.log() 和分离字符输出下文。
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
12. 用 __substr__ 函数将字符串 __because because because__ 从此句子 __'You cannot end a sentence with because because because is a conjunction'__ 中分离。
### 作业:难度水平 3
1. 'Love is the best thing in this world. Some found their love and some are still looking for their love.' 计算这个句子里面有多少个 __love__
2. 用 __match()__ 函数计算 __'You cannot end a sentence with because because because is a conjunction'__ 这个句子里有多少个 __because__
3. 美化下方文字并找到出现频率最高的词。(提示:用 replace 和 正则表达式)
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.' 通过从字符串中提取数字,计算这个人的年收入。
🎉 恭喜!🎉
[<< 第一天](../readMe.md) | [第三天 >>](../第三天_布尔值_运算符_日期/第三天_布尔值_运算符_日期.md)
Loading…
Cancel
Save