JavaScript 语言的相关知识,内容包括数据类型、函数、对象、类、… 语法。

一、数据类型

JavaScript 有七种数据类型,口诀是“四基两空一对象”

  • 数值(Number)
  • 字符串(String)
  • 逻辑值(Boolean)
  • Symbol
  • undefined
  • null
  • object

在 JavaScript 中,数组和函数是特殊的对象

  1. let number = 1
  2. let string = Hello
  3. let object = {name:'Eddie',age:18}
  4. let array = [1,2,3]
  5. let f = function(){}

一些逻辑值判断

  • 除了这五个 falsy 值,其他都是 True
  1. 0
  2. NaN
  3. ''
  4. undefined
  5. null

二、函数

1. 定义时函数的写法

JS 有三种函数写法,具名函数和匿名函数有 this,箭头函数无 this

  1. // 具名函数
  2. function f(x){console.log(x+1)}
  3. f(1) // 2
  4. f(2) // 3
  5. // 匿名函数
  6. let f2 = function(x){console.log(x+2)}
  7. f2(1) // 3
  8. f2(2) // 4
  9. // 箭头函数
  10. let f3 = (x)=>{console.log(x+3)}
  11. f3(1) // 4
  12. f3(2) // 5

2. 对象中函数的写法

  • 对象中的函数叫做“方法”
  • 写法 1、2 有 this,写法 3 无 this
  1. let object = {
  2. f(x){console.log(x+1)},
  3. f2: function(x){console.log(x+2)},
  4. f3: (x)=>{console.log(x+3)}
  5. }
  6. object.f(1)
  7. object.f2(1)
  8. object.f3(1)

个人最喜欢喜欢第一种写法,最简洁

三、对象

  • 对象是一系列属性的集合
  • 对象中的函数叫“方法”
  1. let object = {name:'Eddie',age:18}

三、类

  • 定义类和继承类
  1. // 定义一个矩形类
  2. class Reactangle{
  3. constructor(length,width){
  4. this.length = length
  5. this.width = width
  6. this.name = "reactangle"
  7. }
  8. area(){
  9. return this.length*this.width
  10. }
  11. perimeter(){
  12. return (this.length + this.width)*2
  13. }
  14. }
  15. let reactangle = new Reactangle(3,4)
  16. console.log(reactangle.name) // reactangle
  17. console.log(reactangle.area()) // 12
  18. console.log(reactangle.perimeter()) // 14
  19. // 定义一个正方形类,继承矩形类,并可以计算出以它的边长形成的立方体
  20. class Square extends Reactangle{
  21. constructor(width){
  22. super()
  23. this.length = width
  24. this.width = width
  25. this.name = "square"
  26. }
  27. volumn(){
  28. return Math.pow(this.width,3)
  29. }
  30. }
  31. let square = new Square(5)
  32. console.log(square.name) // square
  33. console.log(square.area()) // 25
  34. console.log(square.perimeter()) // 20
  35. console.log(square.volumn()) // 125

四、… 语法

  • … 扩展运算法能够把对象和数组拆分开

参考博客:ES6 扩展运算符
_

1. 数组中 … 的使用

  1. let array = [1,2,3,4,5]
  2. console.log(...array) // 1 2 3 4 5
  3. console.log(0,...array,6) // 0 1 2 3 4 5 6

2. 对象中 … 的使用

  1. let object = {name:'Eddie',age:18}
  2. let object2 = {...object,hobby:'music'}
  3. console.log(object2) // {{name:'Eddie',age:18},hobby:'music'}

「@浪里淘沙的小法师」