ES6快速入门

1. 变量声明const和let

  • let表示变量(局部变量)
  • const表示常量(JAVA的final)

2. 模板字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const name = 'lux';
console.log(`hello ${name}`) //hello lux

//多行文本--使用反引号
// ES5
var msg = "Hi \
man!
"
// ES6
const template = `<div>
<span>hello world</span>
</div>`

// 1.includes:判断是否包含然后直接返回布尔值
const str = 'hahay'
console.log(str.includes('y')) // true

// 2.repeat: 获取字符串重复n次
const str = 'he'
console.log(str.repeat(3)) // 'hehehe'
//如果你带入小数, Math.floor(num) 来处理
// s.repeat(3.1) 或者 s.repeat(3.9) 都当做成 s.repeat(3) 来处理

// 3. startsWith 和 endsWith 判断是否以 给定文本 开始或者结束
const str = 'hello world!'
console.log(str.startsWith('hello')) // true
console.log(str.endsWith('!')) // true

3. 函数

默认参数,类似于python

1
2
3
function action(num = 200) {
console.log(num)
}

箭头函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
x => x * x
//等于下面
function (x) {
return x * x;
}

x => {
if (x > 0) {
return x * x;
}
else {p
return - x * x;
}
}

// 两个参数:
(x, y) => x * x + y * y

// 无参数:
() => 3.14

// 可变参数:
(x, y, ...rest) => {
var i, sum = x + y;
for (i=0; i<rest.length; i++) {
sum += rest[i];
}
return sum;
}

//返回对象
x => ({ foo: x })

4. 拓展的对象功能

对象初始化简写

1
2
3
4
5
6
function people(name, age) {
return {
name, // name : name
age // age : age
};
}

浅克隆

5. 更方便的数据访问–解构

1
2
3
4
5
6
7
8
9
10
11
12
//对象
const people = {
name: 'lux',
age: 20
}
const { name, age } = people
console.log(`${name} --- ${age}`)
//数组
const color = ['red', 'blue']
const [first, second] = color
console.log(first) //'red'
console.log(second) //'blue'

Object.assign() 可以把任意多个源对象自身可枚举的属性拷贝给目标对象,然后返回目标对象。第一参数即为目标对象。在实际项目中,我们为了不改变源对象。一般会把目标对象传为{}

6. Spread Operator 展开运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//数组
const color = ['red', 'yellow']
const colorful = [...color, 'green', 'pink']
console.log(colorful) //[red, yellow, green, pink]

//对象
const alp = { fist: 'a', second: 'b'}
const alphabets = { ...alp, third: 'c' }
console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"

//数组
const number = [1,2,3,4,5]
const [first, ...rest] = number
console.log(rest) //2,3,4,5
}

7. import导入模块、export导出模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//全部导入
import people from './example'

//有一种特殊情况,即允许你将整个模块当作单一对象进行导入
//该模块的所有导出都会作为对象的属性存在
import * as example from "./example.js"
console.log(example.name)
console.log(example.age)
console.log(example.getName())

//导入部分
import {name, age} from './example'

// 导出默认, 有且只有一个默认
export default App

// 部分导出
export class App extend Component {};

作者:陈嘻嘻啊
链接:https://www.jianshu.com/p/287e0bb867ae
來源:简书

lightquant wechat
欢迎您订阅灯塔量化公众号!