ES6-基础语法
1. let & const
1.1. let
声明变量用let
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>let</title>
</head>
<body>
<script>
// define variables
let a;
let b,c,d;
let e = 100;
let f = 521, g = 'iloveyou', h = [];
//1. can not state variables repeatedly
// let star = 'michael';
// let star = 'father';
//2. block level scope global, function, eval
// if else while for
// {
// let girl = 'lisa from blackpink';
// }
// console.log(girl);
//3. there is no variable promotion
// console.log(song);
// let song = 'love the way you lie';
//4. the scope chain is not affected
{
let school = 'school w3';
function fn(){
console.log(school);
}
fn();
}
</script>
</body>
</html>
1.2. cont
tips:
- 对象属性修改和数组元素变化不会发出const错误
- 声明 对象类型使用const,非对象类型声明选择let
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>const 定义常量</title>
</head>
<body>
<script>
// state constant variables
const SCHOOL = 'school w3';
// 1. must assign an initial value
// const A;
// 2. normal constants use uppercase (defaul rule)
// const a = 100;
// 3. vale of constant can not be changed
// SCHOOL = 'school w3';
// 4. block level scope
{
const PLAYER = 'michael jordan';
}
console.log(PLAYER);
//5. it is not counted as changes to constancts to change the values of elements of arrays and objects, and no error is reported
const TEAM = ['UZI','MXLG','Ming','Letme'];
// TEAM.push('Meiko');
</script>
</body>
</html>
2. 模板字符串
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>template string</title>
</head>
<body>
<script>
// ES6 introduces a new way to declare string 『``』 '' ""
//1. statement
// let str = `here is the string`;
// console.log(str, typeof str);
//2. a newline character can appear directly in the content
let str = `<ul>
<li>michael</li>
<li>harry</li>
<li>lisa</li>
<li>allen</li>
</ul>`;
//3. variables splice
let lovest = 'michael';
let out = `${lovest} is the best developer in my heart!!`;
console.log(out);
</script>
</body>
</html>
3. 解构赋值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>decontractive assignment of a variable</title>
</head>
<body>
<script>
//ES6 allows to extract values from arrays and objects and assign to variales in a certain pattern,
//assignment of decontruction。
//1. array deconstruction
const F4 = ['Lisa','Jennie','Rose','Jisoo'];
let [lisa, jennie, rose, jisoo] = F4;
console.log(lisa);
console.log(jennie);
console.log(rose);
console.log(jisoo);
//2. object deconstruction
const zhao02 = {
name: 'lisa',
age: '18',
dance: function(){
console.log("Lisa is good at dancing!!!");
}
};
// let {name, age, dance} = zhao02;
// console.log(name);
// console.log(age);
// console.log(dance);
// dance();
//
let {dance} = zhao02;
dance();
</script>
</body>
</html>
4. 对象的简化写法
//ES6 allows to write variables and functions directly inside curly braces as properties and methods of objects
//makes it simple and specific
var nameWold = 'michael'
var change = function(){
console.log('michael can change the world!!!')
}
const michael = {
nameWold,
change,
dance: function(){
console.log('michael can dance in the object!!!')
}
}
console.log('nameWold: ', nameWold)
michael.change()
michael.dance()
5. 箭头函数
basic information about arrow function
// ES6 allows to define a function by =>
// 1. define arrow function
// define a funtion by traditional way
function fun1(){
console.log('here is the logging from fun1!!!')
}
fun1()
var fun2 = function(para){
console.log('here is the log from fun2 with param!!!')
}
fun2()
// arrow functon
var arrowFun = () => {
console.log('here is the log from arrow fun !!!')
}
arrowFun()
var arrowFunWithParam = (a, b) => {
return a + b
}
console.log('a + b: ', arrowFunWithParam(6, 10))
// abbreviated form of arrow function
var arrowFunWithAbbr = a => a * a
console.log('a * a: ', arrowFunWithAbbr(10))
// 2. this in the arrow function
// in arrow function: this is static, this always points to the value of this in the scope in which the function is declared
function getThisFromFunction(){
console.log('this from traditional function:', this);
}
getThisFromFunction() // <ref *1> Object [global]
var getThisFromArrowFunc = () => {
console.log('this from arrow function:', this)
}
getThisFromArrowFunc() // {}
const MICHAEL = {
price: '$99'
}
// call the function by keyword key
getThisFromFunction.call(MICHAEL) // { price: '$99' }
getThisFromArrowFunc.call(MICHAEL) // {}
// 3. arrow function can not instantiate an object as a construct
let Product = (count, price) => {
this.count = count
this.price = price
}
// let product = new Product(100, 200)
// console.log('product: ', product) // TypeError: Product is not a constructor
let CommonProduct = function(count, price) {
this.count = count
this.price = price
}
let commonProduct = new CommonProduct(100, 200)
console.log('common product: ', commonProduct) // CommonProduct { count: 100, price: 200 }
// 4. arrow function can not use arguments variables
let commonFun = function(){
console.log('arguments from function: ', arguments)
}
commonFun(1, 3, 5, 9)
let arrowFunction = () => {
console.log('arguments from arrow function: ', arguments)
}
// arrowFunction(1, 3, 5, 9) //
arrow function practice
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>arrow function practice</title>
<style>
div {
width: 200px;
height: 200px;
background: #58a;
}
</style>
</head>
<body>
<div id="ad"></div>
<script>
// requirement 1: the color is changed to be pink after 2 seconds since click the div
// get the element
let ad = document.getElementById('ad')
// bind event
// implement by common function
// ad.addEventListener("click", function(){
// // save this
// let _this = this
// console.log('_this: ', _this) // ad
// setTimeout(function(){
// console.log('this: ', this) // window w
// // this.style.background = 'pink'
// _this.style.background = 'pink'
// }, 2000)
// })
// implement by arrow function
ad.addEventListener('click', function(){
setTimeout(() => {
console.log('this: ', this)
this.style.background = 'pink'
}, 2000)
})
// requirement 2: return the odd elements from an array
const arr = [1,6,9,10,100,25];
const result = arr.filter(function(item){
if (item % 2 === 0){
return true
}else{
return false
}
})
const result2 = arr.filter(item => item % 2 === 0)
console.log('result: ', result)
console.log('result2: ', result2)
</script>
</body>
</html>
6. rest 参数
ES6 引入rest参数,用于获取函数的实参,用来替代arguments
rest参数非常适合不定个数参数函数的场景
// ES6 introduces rest arguments, which take arguments to functions instead of arguments
// rest arguments are well suited to scenarios where functions with an indefinite number of arguments are used
// ES5
function girlGroup(){
console.log(arguments)
}
girlGroup('Lisa', 'Rose', 'Jennie', 'Jisoo') // [Arguments] { '0': 'Lisa', '1': 'Rose', '2': 'Jennie', '3': 'Jisoo' }
// rest arguments
function newGirlGroup(...args){
console.log(args)
}
newGirlGroup('Lisa', 'Rose', 'Jennie', 'Jisoo') // [ 'Lisa', 'Rose', 'Jennie', 'Jisoo' ]
// rest param must be placed at the end of the parameters
function newGirlGroupFromKorean(member1, member2, ...args){
console.log(member1)
console.log(member2)
console.log(args)
}
newGirlGroupFromKorean('Lisa', 'Rose', 'Jennie', 'Jisoo')
// Lisa
// Rose
// [ 'Jennie', 'Jisoo' ]
7.spread 扩展运算符
扩展运算符(spread)也是三个点(…), 好比rest参数的逆运算, 讲一个数据准尉用逗号分割的参数序列,对数组进行解包
// ... expansion operator converts an array to a comma-separated sequence of arguments
// 1. expand array
// state an array
const blackpink = ['lisa', 'rose', 'jennie', 'jisoo']
// state a function
function girlGroup(){
console.log(arguments)
}
girlGroup(...blackpink) // [Arguments] { '0': 'lisa', '1': 'rose', '2': 'jennie', '3': 'jisoo' }
// 2. expand object
// state objects first
const object1 = {
field1:'fieldVaule',
field2:'field2Value'
}
const object2 = {
field3:'fieldVaule',
field4:'field2Value'
}
const contactObject = {...object1, ...object2}
console.log('contactObject: ', contactObject)
// array concat
const part1 = ['lisa', 'rose']
const part2 = ['jennie', 'jisoo']
const concatArray = part1.concat(part2).concat(part2)
console.log('concatArray: ', concatArray)
// array clone
const cloneArray = [...blackpink]
console.log('cloneArray: ', cloneArray)