<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Study ES6</title>
</head>
<body>
<div>
<span>Hello ES6</span>
</div>
</body>
<script>
var var1 = 'var声明的变量会出现越域的情况,var可以声明多次,var会变量提升。';
writeLine(var1);
let let1 = 'let声明的变量有严格局部作用域,let变量只能声明一次,let不存在变量提升。';
writeLine(let1);
var v = 'JavaScript 变量提升,JavaScript 中,函数及变量的声明都将被提升到函数的最顶部。'
+'变量可以在使用后声明,也就是变量可以先使用再声明';
writeLine(v);
//const声明只读变量,常量
const v3 = 1;
//定义数组
let arr = [1, 2, 3];
//数组解构
const [a, b, c] = arr;
console.log(a, b, c);
//定义对象
const person = {
name: "zhangshuai",
age: 26,
language: ['java', 'js', 'css']
}
//打印json格式数据
writeLine(JSON.stringify(person));
//对象解构,将name属性的值赋值给abc
const {
name: abc,
age,
language
} = person;
console.log(abc, age, language);
//字符串常用方法
let str = 'hello.vue';
console.log(str.startsWith("hello"));
console.log(str.endsWith('.vue'));
console.log(str.includes('e'));
console.log(str.includes("hello"));
//模板字符串 使用 ``
let ss = `<div>
<span>hello world</span>
</div>`;
writeLine(ss);
//字符串插入变量和表达式。变量名写在${}中,${}可以放入JavaScript表达式
let info = `我是${abc},今年${age}了。我想说${say()}`;
writeLine(info);
function say() {
return "I love JAL!!!";
}
//函数优化
//在ES6之前,无法给一个函数参数设置默认值,只能采用变通写法
function add(a, b) {
//判断是否为空,为空默认为1
b = b || 1;
return a + b;
}
writeLine(add(12));
//ES6可以这么写,直接给参数写上默认值,没传参就自动使用默认值
function add1(a, b = 1) {
return a + b;
}
writeLine(add1(13));
//不定参数
function add3(...value) {
writeLine(value.length);
}
add3(1, 2, 3, 4);
//箭头函数
var print=obj=>writeLine(obj);
print("箭头函数");
var hello2=(param)=>writeLine(param.name);
hello2(person);
//箭头函数+结构表达式
var hello3=({name})=>writeLine(name);
hello3(person);
//对象优化
const target={a:1};
const source1={b:1};
const source2={c:1};
//Object.assign方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)。
Object.assign(target,source1,source2)
writeLine(JSON.stringify(target));
//对象声明简写
const gender='男';
const address='山东济宁';
const person1={gender:gender,address:address};
writeLine(JSON.stringify(person1));
//属性名和变量名一样的话可以简写成这样
const person2={gender,address};
writeLine(JSON.stringify(person2));
//对象的函数属性简写
let person3={
name:"zhangdashuai",
age:25,
dream:function (who){
writeLine(this.name+'做梦梦见'+who);
},
//箭头函数this不能使用,可以使用对象。属性
dream2:who=>writeLine(person3.name+'做梦梦见'+who),
dream3(who){
writeLine(person3.name+'做梦梦见'+who)
writeLine(this.name+'做梦梦见'+who)
}
}
person3.dream('JAL1');
person3.dream2('JAL2');
person3.dream3('JAL3');
//const 修饰的对象属性可以修改,但是修饰的常量就不可以修改
//原因:const指针指向的地址不可以改变,指向地址的内容是可以改变的。
//因为const只是保证对象的指针不改变,而对象的内容改变不会影响到指针的改变,所以对象的属性内容是可以修改的。
//换行打印
function writeLine(s) {
document.write(s + "<br>")
}
</script>
</html>