<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>解构赋值</title>
<script>
// 对象解构赋值, 符号{}
{
let zhao = {name : "zhaozhao", age: 10};
// 传统获取值的方式(键为字符串格式)
console.log("name:", zhao["name"], "age:", zhao["age"]);
// 解构赋值的方式(会自动匹配相应的键, 如果解构了不存在的键,则值为undefined)
let {age, name, hobby} = zhao;
console.log("name:", name, "age:", age, "hobby:", hobby);
}
// 数组解构赋值, 符号[]
{
let zhao = [123, "Mac", "iPhone", 345]
let [zhao1, zhao2, zhao3, zhao4] = zhao;
console.log("数组解构赋值结果:", zhao1, zhao2, zhao3, zhao4);
}
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6新模板语法</title>
<script>
window.onload = function(){
var el = document.getElementById("app");
{
let age = 5;
let name = 'YY';
let oldHtml = "<p>"+"age = "+age;
oldHtml = oldHtml + " name = "+name;
oldHtml = oldHtml + "</p>";
el.innerHTML = oldHtml;
}
{
let age = 13;
let name = "zhaozhao";
// 新的模板语法${}需要配合``使用,并且支持换行
let newHtml = `<p>
age = ${age}
name = ${name}
</p>`;
let tmpHtml = el.innerHTML;
// 注意innerHTML的写法
el.innerHTML = tmpHtml + newHtml;
}
}
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6常用语法: 函数默认参数</title>
<script>
function DiyConsoleLog(name="zhao", age=15){
console.log("姓名:", name, "年龄:", age)
}
// 无参数调用
console.log("无参数调用:")
DiyConsoleLog()
// 只传一个参数
console.log("只传一个参数:")
DiyConsoleLog("YY")
// 传两个参数
console.log("传两个参数(正常调用):")
DiyConsoleLog("YY", 12)
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6之箭头函数</title>
<script>
window.onload = function(){
// 箭头函数的用法
{
let NewArray = [1, 4];
// 普通函数
NewArray.map(function addOne(item){
result = item + 1
console.log("普通函数:",this,"==>",result)
});
// 箭头函数
NewArray.map((item)=>{
result = item + 1
console.log("箭头函数",this,"==>",result)
});
}
console.log("箭头函数与普通函数的区别: ")
// 箭头函数的优势
{
function wrapperfn (){
// 普通函数
this.map(function addOne(item){
result = item + 1
console.log("普通函数:",this,"==>",result)
});
// 箭头函数
this.map((item)=>{
result = item + 1
console.log("箭头函数",this,"==>",result)
});
}
let NewArray = [12, 34];
wrapperfn.call(NewArray);
}
}
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
Babel相当于一个翻译, 可以将ES6的语法,装换为ES5的语法
为了方便安装以及后续的管理, 我们使用npm管理工具, 安装babel
npm init
, 一路回车, 会在babel-text生成配置文件package.json
npm install --save-dev babel-preset-es2015
`
npm install --save-dev babel-preset-react
npm install --save-dev babel-preset-stage-3
.babelrc
, 将刚刚安装的三个规则配置到.babelrc
, 保存文件{
"presets": [
"es2015",
"react",
"stage-3"
],
"plugins":[]
}
babel-cli
之间安装到babel-test内npm install --save-dev babel-cli
build
(命令作用为: 把根目录下的js文件夹内所有es6语法的js文件, 在保持原文件名的基础上, 转码输出到lib文件夹)"build": "babel js -d lib"
npm run build
转换, 查看结果