一、了解ES6
1)ES6官網:http://www.ecma-international.org/ecma-262/6.0/
2)Javascript是ECMAScript的實作和擴展
3)ES學習建議:
- 基礎語法(包括與舊版的差異優劣;新版有哪些坑等等)
- 應用場景
- 多在專案中應用
補充:VSCode的插件Live Server的作用:
- 頁面更改后自動重繪
- 使用的是http協議而非file://
二、ES6特性入坑
1)let\const
let
// let定義變數
let name = "zhangsan"
// var會造成變數穿透
for(var i=0;i<5;i++){
console.log(i);
};
console.log("===這里就是變數穿透===>" + i) // 結果:===這里就是變數穿透===>5
// let不會造成變數穿透
for(let i=0;i<5;i++){
console.log(i);
};
console.log("===這里就是變數穿透===>" + i) // 結果:i is not defined
const:
// ES5
Object.defineProperty(window, 'es', {
value:'es6',
writable:false
})
console.log(es) // window.es,括號內為簡寫;結果:es6
window.es = 'es2015'
console.log(window.es) // 結果:es6
// ES6 const:常量
// 1
const es = 'es6'
console.log(es) // 結果:es6
//es = 'es2015' // 這行報錯
console.log(es)
// 2.const 常量名不允許重復宣告
var str = 'es6'
var str = 'es2015'
console.log(str) // es2015
// 3
// const 宣告的常量 不屬于 頂層物件window
// var 宣告的變數 屬于 頂層物件window
// 4.const不存在常量提升
// var變數提升
console.log(str) // 結果:undefined
var str = 'es6'
// 相當于
var str
console.log(str) // 結果:undefined
str = 'es6'
// 5.const宣告的常量具有塊級作用域
// var
if(true){
var strsix = 'es6'
}
console.log(strsix) // 結果:es6
const宣告常量的本質
const宣告的常量真的不可以改變嗎

const esObj = {
name:'es6',
year:2015,
}
esObj.name = 'es2015'
console.log(esObj.name) // 結果:es2015
const esObj = {
name:'es6',
year:2015,
}
Object.freeze(esObj)
esObj.name = 'es2015'
console.log(esObj.name) // 結果:es6
const arr = ['es6', 'es7', 'es8']
Object.freeze(arr)
arr[0] = 'es2015'
console.log(arr[0]) // 結果:es6
const esObj = {
name:'es6',
year:2015,
extension:['es7', 'es8'],
}
// Object.freeze(esObj)
myFreeze(esObj)
esObj.extension[0] = 'es2016'
console.log(esObj.extension[0]) // 結果:es7
// 對深層次的資料進行凍結
function myFreeze(obj){
Object.freeze(obj)
// ES5的forEach;keys()方法得到的是陣列
Object.keys(obj).forEach(function(key){
if(typeof obj[key] === 'object'){
myFreeze(obj[key])
}
});
}
// 建議優先使用const
2)箭頭函式
2-1箭頭函式
// 1-1.原始寫法
const sum = function(x, y){
return x + y
}
const res = sum(4, 4)
console.log(res)
// 1-2
// 默認引數 給引數串列設定初始值
function add(a=100,b=100) {
console.log(a,b);
}
// 執行方法,會用默認值填充,列印出來100,100
add();
// 覆寫默認值列印 結果是1,2
add(1,2);
// 2.箭頭函式寫法
const sum2 = (x, y) => {
return x + y
}
// 相當于: const sum2 = (x, y) => x + y
const res2 = sum2(5, 5)
console.log(res2)
// 3.只有一個形參,小括號可省略
// 4
const btnObj = document.querySelector('#btn')
// console.log(btnObj)
btnObj.addEventListener('click', () => {
/*箭頭函式里面沒有this,當需要在箭頭函式里用到this時,
它會通過當前的作用域鏈,向它上層的作用域內去找this指向,到底
指向的誰*/
console.log(this) // 結果:window
this.style.backgroundColor = '#f00'
})
2-2箭頭函式任何場景都可以使用嗎
// 1
const obj = {
name1:'cy',
showName:function(){
console.log('名字:'+ this.name1) //名字:cy
},
// 簡寫:
showName(){
console.log('名字='+ this.name1) //名字=cy
},
showName:() => {
console.log('名字:'+ this.name1) // 名字:undefined
},
}
obj.showName()
// 2
/*function sum2(x, y){
// function里面的關鍵字arguments,arguments能夠取到形參的值和其它東西
console.log(arguments)
}
sum2(3, 3)*/
const sum = (x, y) => {
// 在箭頭函式中不能使用arguments
console.log(arguments)
return x + y
}
sum(4, 4) // arguments is not defined
// 3
// 在ES5中使用函式模擬一個類
function Course(mame, price){
this.name = name
this.price = price
}
const c1 = new Course('es', 500)
console.log(c1)
// ES5中類的方法定義在原型中
Course.prototype.study = function(){
console.log(`學習: ${this.name}`) // ES6模板字串
}
c1.study()
// ES6箭頭函式不能作為建構式
const Course = (mame, price) => {
this.name = name
this.price = price
}
// TypeError:Course is not a constructor
const c2 = new Course('es', 500)
console.log(c2)
// ES6箭頭函式不能定義原型方法
Course.prototype.study = () => {
console.log(`學習: ${this.name}`) // ES6模板字串
}
c1.study()
3)解構賦值
3-1解構賦值
// 1
const course = {
name:'es6',
price:500,
teacher:{
name2:'cy',
age:89,
},
say(){
console.log(this) // this指window
console.log('名字');
}
}
/*傳統的做法:
var name = course.name
var price =course.price
course.say()
*/
/*const {name2, price} = course
默認情況name,price必須是JSONKey.
console.log(name2) //結果:undefined */
const {name, price, teacher:{name2, age}, say} = course
console.log(name, price, name2, age)
say()
// 2
const course = {
name:'es6',
price:500,
teacher:{
name:'cy',
age:89,
}
}
// courseName:為別名,可以用冒號取別名
const {name:courseName, price, teacher:{name, age}} = course
console.log(courseName, price, name, age)
// 3
const arr = ['es6', 'es7', 'es8']
const [a, b, c] = arr
console.log(a, b, c)
3-2準確的使用解構賦值
- 函式引數
- 函式回傳值
- 變數互換
- JSON應用
- Ajax請求應用
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.js"></script>
<script>
// 1.作為函式的形式引數使用
/*const sum = arr =>{
let res = 0
for(let i = 0; i < arr.length; i++){
res += arr[i]
}
console.log(res)
}
sum([1, 2, 3])
const sum = ([a, b, c]) =>{
console.log(a + b + c)
}
sum([1, 2, 3]) */
const foo = ({name, age, school='默認值,傳值則改'}) => {
console.log(name, age, school)
}
foo({
name:'張三',
age:20
})
// 2.作為函式的回傳值使用
const foo = () => {
return {
name:'cy',
age:20
}
}
const {name, age} = foo()
// 3.兩個變數的值互換
let a = 1
let b = 2
[b, a] = [a, b]
console.log(a, b) // 結果:2 1
// 4.JSON應用
const json = '{"name":"es","price":"500"}'
/*const obj = JSON.parse(json)
console.log(obj) // {name:"es", price:"500"} */
const {name, price} = JSON.parse(json)
console.log(name, price)
// 5.Ajax請求應用
/*axios.get('./data.json').then(function(res){
console.log(res)
})*/
axios.get('./data.json').then(res => {
console.log(res.data)
})
// axios.get('./data.json').then(res => {console.log(res.data)})相當于
axios.get('./data.json').then(({data}) => {
console.log(data)
})
axios.get('./data.json').then(({data:{name, type}}) => {
console.log(name, type)
})
</script>
4)模板字串
const name = 'itcast'
console.log(`hello ${name}`)
5)物件簡寫
如果一個物件中的key和value的名字一樣的情況下可以定義成一個,
function person(name, age) {
// return {name:name,age:age};
// 物件簡寫
return {name, age};
};
// 呼叫和執行
var json = person("小花花美美", 20);
console.log(json.name, json.age);
//========= 實戰應用 =============
//<button onclick="login()">登錄</button>
function login() {
var username = $("#username").val();
var password = $("#password").val();
// 發送ajax
$.ajax({
type: "post",
// 物件簡寫
data: {username, password},
// 原始寫分
//data:{username:username,password:password},
success() {
}
});
}
6)傳播運算子【...】
把一個物件的屬性傳播到另外一個物件中
// ==== ... 物件融合====
var person1 = {
name: '小飛飛',
age: 16,
};
var person2 = {
...person1,
gender:1,
tel:13478900
};
console.log(person2);
// ==== ... 物件取值====
var person3 = {
name:"李四",
gender:1,
tel:"11111",
address:'廣州'
};
// ...person4 把剩下沒取走給我
var {name,gender,...person4} = person3
console.log(name)
console.log(age)
console.log(person4)
// 模擬后臺:異步查詢回傳用戶資料
function findUsers(){
$.get("xxxxx",function(res){
var res = {
pages:11,
pageSize:10,
pageNo:1,
firstFlag:true,
lastFlag:false,
total:123,
data:[{},{},{},{}],
};
// ... 物件取值
var {data:users,...pagesjon} = res;
// 等價于
/* var users = res.data;
var pagesjon = {
res = {
pages:11,
pageSize:10,
pageNo:1,
firstFlag:true,
lastFlag:false,
total:123,
}; */
})
}
7)陣列map和reduce方法
map
方法可以將原陣列中的所有元素通過一個函式進行處理并放入到一個新陣列中并回傳該新陣列
let arr = ['1', '20', '-5', '3'];
var newarr = arr.map(value =https://www.cnblogs.com/yulingzhiling/archive/2022/01/27/> {
return parseInt(value) * 2;
});
console.log("原陣列:" + arr)
console.log("new陣列:" + newarr)
reduce
reduce(function()(必須),初始值(可選) )
- 第一個引數是上一次reduce處理的結果
- 第二個引數是陣列中要處理的下一個元素
reduce() 會從左到右依次把陣列中的元素用reduce處理,并把處理的結果作為下次reduce的第一個引數,如果是 第一次,會把前兩個元素作為計算引數,或者把用戶指定的初始值作為起始引數
let arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var result = arr2.reduce((a, b) => a + b);
console.log(result);
作者:御靈之靈轉載請注明原文鏈接:https://www.cnblogs.com/yulingzhiling/p/15849730.html若標題中有“轉載”字樣,則本文著作權歸原作者所有,若無轉載字樣,本文著作權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421836.html
標籤:其他
上一篇:JS的一些物件
下一篇:在js中如何區分深拷貝與淺拷貝?
