JS 進階(9) ECMAScript6 基礎入門:變數、函式、解構賦值、陣列、字串、面向物件、json、promise
一、ES6是啥
-
ECMAScript 和 JavaScrip的關係 簡單的說ECMA 是一個標準,任何語言都可以去實現這個標準,但目前為止只有javascript 實現了。所以也就預設認為ECMAScript就是javascript。 ECMAScript 簡稱 ECMA 或 ES。
-
ECMAScript 歷史版本 1996, ES1.0 Netscape 將 JS 提交給 ECMA 組織,ES 正式出現 1999, ES3.0 被廣泛支援 2011, ES5.1 成為 ISO 國際標準 2015, ES6.0 正式釋出
二、ES6的相容性
-
ES6(ES2015) 支援的環境 IE10+, Chrome, FireFox, 移動端, NodeJS
-
解決不相容辦法,編譯、轉換
- 線上轉換
<script src="browser.js" charset="utf-8"></script>
<script type="text/babel">
let a = 3;
let b = 6;
</script>
- 提前編譯 使用babel編譯工具可以將寫好的ES6程式碼編譯成ES5(相容IE8等),甚至也可以編譯成ES3(相容各種低版本的瀏覽器)
三、變數 let 和 常量 const
- var 的問題
- 可以重複宣告,沒有報錯和警告
- 無法限制修改
- 沒有塊級作用域, { }
-
let 和 const
- 不能重複宣告
- 都是塊級作用域, { } 塊內宣告的,塊外無效
- let 是變數,可以修改
- const 是常量,不能修改
- 塊級作用域舉例 ES5 在ES5中我們是使用匿名函式的函式作用域來當做塊級作用域來使用的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload= function () {
var aBtn = document.getElementsByTagName('input')
for (var i = 0; i < aBtn.length; i++) {
(function (i) {
aBtn[i].onclick = function () {
alert(i)
}
})(i)
}
}
</script>
</head>
<body>
<input type="button" value="按鈕1">
<input type="button" value="按鈕2">
<input type="button" value="按鈕3">
</body>
</html>
ES6
在ES6中,直接將變數宣告var
改為let
就解決了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload= function () {
var aBtn = document.getElementsByTagName('input')
for (let i = 0; i < aBtn.length; i++) {
aBtn[i].onclick = function () {
alert(i)
}
}
</script>
</head>
<body>
<input type="button" value="按鈕1">
<input type="button" value="按鈕2">
<input type="button" value="按鈕3">
</body>
</html>
四、函式
1.函式-箭頭函式
- 箭頭函式,就是函式的簡寫,可以用,可以選擇不用。(我還是推薦用,主要是因為懶)
- 如果只有一個引數,() 可以省
- 如果只有一個return,{}可以省,return可以省
ES5:
普通函式
function name(){
...
}
匿名函式
function(){
}
ES6:
去掉關鍵字function
和函式名,使用=>
連線引數列表和函式體。
let name = () =>{
....
}
1.如果只有一個引數,() 可以省;沒有引數,()不能省
let show1 = function () {
console.log('abc')
}
可以寫成
let show1 = () => {
console.log('abc')
}
let show2 = function(a){
return a*2;
}
可以寫成
let show2 = a=>{
return a*2;
}
2.如果只有一個return,{}可以省,return可以省
let show = function (a) {
return a*2
}
可以寫成
let show = a => a * 2
2.函式-引數
- 引數擴充套件/展開 …args 收集剩餘的引數,必須當到最後一個引數位置 展開陣列,簡寫,效果和直接把陣列的內容寫在這兒一樣
ES5: ES5中我們使用函式中的類陣列物件argments可以獲取所有引數。
如果要獲取傳入的多餘引數,這如下。
function show(a,b){
for(var i=arguments.length-show.length-2,len=arguments.length;i<len; i++){
console.log(arguments[i]);
}
}
show(1,2,3,4,5,6,7);
ES6:
在引數列表中使用..args
可以將多餘的引數裝入到陣列args
中,再使用..args
就可以將陣列展開。
在ES6要獲取傳入的多餘引數很簡單,使用...args收集多餘的引數
function show(a, b, ...args) {
console.log(a)
console.log(b)
console.log(args)
}
console.log(show(1, 2, 3, 4, 5)) 輸出3,4,5
引數展開
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = [...arr1, ...arr2]
console.log(arr3)
- 預設引數 給函式的引數設定預設引數。
ES5:
function hello(txt){
var str = txt || 'hello poorpenguin';
}
ES6:
function hello(txt='hello poorpenguin'){
}
五、解構賦值
- 解構賦值
- 左右兩個邊結構必須一樣
- 右邊必須是合法的
- 宣告和賦值賦值不能分開(必須在一句話裡完成宣告和賦值)
左右兩個邊結構必須一樣
let [a, b, c] = [1, 2, 3]
console.log(a, b, c); 1 2 3
let {x, y, z} = {x: 1, y: 2, z: 3}
console.log(x, y, z);
let [{a4, b2}, [num1, num2, num3], num4 ,str2] = [{ a4: 1, b2: 2 }, [1, 2, 3], 8, 'str'];
console.log(a4, b2, num1, num2, num3, num4, str2);
可以自行選擇解析的粒度
let [json, arr, num, str] = [{ a: 1, b: 2 }, [1, 2, 3], 8, 'str']
console.log(json, arr, num, str);
這樣式錯誤的
let [a,b] = {a:12,b:45};
右邊必須是合法的
這樣式錯誤的
let {a,b} = {12,5}
宣告和賦值賦值不能分開,必須在一句話
這種是錯誤的。
let [a,b];
[a,b] = [12,5];
六、陣列
ES6中新增了4個數組的方法
- map 對映(參考jquery中的map)
- reduce 彙總
- filter 過濾器
- forEach 迴圈(迭代)
map 對映
可以遍歷一個數組,對陣列中的值進行操作,不改變原陣列,並返回一個新陣列。
- 我給你10個,你就要返我10個
陣列中的每一項都會作為回撥函式的引數。使用return
才可以將值返回給新陣列。
例子1:
let arr = [2,6,1,40];
let newArr = arr.map(function(item){
return item*3;
});
console.log(newArr);
輸出[6, 18, 3, 120]
可以使用ES6函式簡寫:
let newArr = arr.map((item)=>item*3);
例子2:
let score = [19,60,56,80,100]; 學生成績
let result = score.map((item)=>item>=60?'及格':'不及格');
console.log(result);
和學生的成績一一對應["不及格", "及格", "不及格", "及格", "及格"]
reduce 彙總
- 彙總就是 一堆出來一個
- 用於比如,算個總數,算個平均
例子1:求和
var arr = [22,33,12,67,98];
temp為回撥函式中上一次的返回值,第一次temp的值為arr[0]
item為陣列項
index為item的下標
var result = arr.reduce(function(temp, item, index){
return temp+item;
});
console.log(result);
232
ES6簡寫
var result = arr.reduce((temp, item, index)=>temp+item);
例子2:求平均值 前幾次都是求和,在最後一次才求平均值
var arr = [22,33,12,67,98];
var result = arr.reduce(function(temp, item, index){
if(index!=arr.length-1){
return temp+item;
}else{ 最後一次加完並求平均值
return (temp+item)/arr.length-1;
}
});
console.log(result);
45.4
ES6簡寫:
var result = arr.reduce(
(temp, item, index)=>(index!=arr.length-1)?temp+item:(temp+item)/arr.length-1
);
filter 過濾器
通過回撥函式return
返回的值來決定值是否保留,true
保留;false
過濾掉。
不改變原陣列,並返回一個新陣列。
例子1:保留能被3整除的數
let arr=[12,34,23,67,23,89,15];
let result = arr.filter(item=>item%3==0);
console.log(result);
例子2:商品價格過濾
let arr=[
{title: '男士衣服1', price:200},
{title: '男士衣服2', price:240},
{title: '女生衣服1', price:2000},
{title: '女生衣服2', price:3000},
{title: '女生衣服3', price:4000},
];
let result = arr.filter(item=>item.price<1000);
console.log(result);
forEach 迴圈
forEach
有兩個引數,第二個引數是下標,可加可不加。
var arr = [32, 12, 45, 9];
var result = arr.forEach(item => console.log(item));
var result = arr.forEach((item, index)=>console.log(item, index));
七、字串
- ES6字串新增兩個方法
- startsWith() 判斷字串以什麼開頭,是返回
true
,否返回false
; - endsWith() 判斷字串以什麼結尾,是返回
true
,否返回false
;
- startsWith() 判斷字串以什麼開頭,是返回
- 字串模板(很重要)
1.新增方法startsWith()
和endsWith()
就是可判斷字串是否以規定的字串開頭和結尾。
例子1:判斷網址是什麼型別的 代替了之前使用正則判斷。
let str='https://www.baidu.com';
if(str.startsWith('https://')){
console.log('加密網址');
}else if(str.startsWith('http://')){
console.log('普通網址');
}else if(str.startsWith('git://')){
console.log('普通網址');
}else if(str.startsWith('svn://')){
console.log('普通網址');
}
例子2:判斷檔案型別 根據副檔名。也是代替了正則判斷。
let str = 'test.txt';
if(str.endsWith('.jpg')){
console.log('圖片檔案');
}else if(str..endsWith('.txt')){
console.log('文字檔案');
}else{
console.log('其他');
}
2.字串模板
該功能很強大,很好用。
- 使用反引號(就是鍵盤1左邊的那個)
- 可以直接把變數的值塞到字串裡,${變數}
- 可以折行
let a = 12
let str1 = `asdf${a}`
console.log(str1)
輸出asdf12
let title = '標題'
let content = '內容'
let str = `<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`
console.log(str)
輸出
<div>
<h1>標題</h1>
<p>內容</p>
八、ES6面向物件
ES5 ES5的面向物件是沒有類這個概念的。
function Person(name,age){
this.name=name||'未知';
this.age=age||18;
}
Person.prototype.sayHello(){
console.log('你好我是'+this.name);
}
var user = new Person('poorpenguin',25);
user.sayHello();
ES6 而ES6中的面向物件很像java。
- 使用關鍵字
class
- 使用
constructor
構造器