• JavaScript = a programming language used for web development 编程语言

1. Variable

  • A variable is a container used to store data.
    • Use const by default
    • Use let only when the value needs to change
const name = "Alan"  
let age = 25

2. Data Types 数据类型

const name = "Alan"     // string 字符串  
const age = 25          // number 数字  
const isStudent = true  // boolean 布尔值  
const emptyValue = null // null  
let x // undefined

3. Array 数组

const nums = [1, 2, 3]
const fruits = ["apple", "banana", "orange"]

4. Object 对象

  • An object stores data as key: value pairs.
const user = {
  name: "Alan",
  age: 25
}

5. Function

function greet(msg) {
  return "Hello, " + msg
}

call function

console.log(greet("Alan")) // Hello, Alan

Structure

function functionName(parameter) {
  return result
}

6. Arrow Function

Arrow function is a shorter way to write a function.
箭头函数就是函数的简写形式。

Normal function

function add(a, b) {
  return a + b
}

Arrow function

const add = (a, b) => {
  return a + b
}

Short form

const add = (a, b) => a + b

7. map() 数组常用方法

  • map() applies an operation to each element in an array and returns a new array.
  • map() 会对数组里的每个元素都处理一次,然后返回一个新数组。

Example

const nums = [1, 2, 3]  
const doubled = nums.map(n => n * 2)
 
// doubled = [2, 4, 6]

8. Destructuring 解构

  • Destructuring lets you take values out of an object more easily.
  • 解构就是把对象里的属性,直接拿出来变成变量。
const user = {
  name: "Alan",
  age: 25
}
 
const { name } = user

9. Template Literal 模板字符串

const name = "Alan"  
const msg = `Hello, ${name}`
 
// Result
"Hello, Alan"

10. if Statement 条件判断

  • if condition is true → run first block
  • otherwise → run else
const age = 20
 
if (age >= 18) {
  console.log("Adult")
} else {
  console.log("Not adult")
}

11. for Loop 循环

for (let i = 0; i < 3; i++) {
  console.log(i)
}
 
// result
0
1  
2

12. for...of 遍历数组

  • Take each item from the array one by one.
const fruits = ["apple", "banana", "orange"]
 
for (const fruit of fruits) {
  console.log(fruit)
}