1. 程式人生 > >初入ES6隨筆

初入ES6隨筆

變量聲明 參數 保留 ssm con 立方根 bsp 輸出 聲明

初入ES6隨筆
var c = a => console.log(a) let a1 = 1; //只在塊兒狀作用域生效的變量聲明 const a2 = 1; //常量聲明,值不可改變,快兒狀作用域 解構賦值語法
let [a3, b3, c3] = [1, 2, 3]; //數組解構賦值 let [a4 = 0, ...b4] = [1, 2, 3, 4] //數組解構賦值 a4 = 1 b4 = [2,3,4] 允許默認值; let {a5, b5} = {a5: "1", b5: "2"} // 對象解構賦值 a5 = 1; b5=2; let {a6: b6, c6: d6} = {a6: "2323", c6: "2"} // 對象解構賦值 將a6的值賦給b6 b6 = 2323; let [a7, b7, c7, d7, e7] = "hello"; //字符串解構賦值 a7="h"; b7="e" .... 字符串擴展

let a8= "hello world!" for(let a8 of ‘let‘){ /*console.log(a8)*/ } //for...of 循環遍歷 "h","e","l" .... a8.indexOf("hello"); //是否包含該字符 //返回在字符串的位置 a8.startsWith("wo"); //true 返回是否包含該字符 a8.startsWith("wo", 6); //true 當前數字的位置是否包含該字符 返回布爾值 a8.endsWith("d!"); //true 最末是否有該字符 a8.endsWith("e",2); //true 第二個是否是該字符 只針對單個字符 a8.includes("hel"); //true 是否包含該字符 返回布爾值 a8.includes("world",6); //true 當前數字的位置是否包含該字符 返回布爾值 a8.repeat(2); //hello world!hello world! 返回一個新的字符串,將該字符串重復N次 ‘x‘.padStart(5, ‘ab‘); // ‘ababx‘ 在數值前補全到指定位數 常用與數字位數的補全 0000012 ‘x‘.padEnd(5, ‘ab‘); // ‘xabab‘ 在數值後補全到指定位數 常用與數字位數的補全 0000012 `${a8}我是ME`; //模板字符串,使用“ ` ” 在${} 中加入js代碼可直接運行並輸出 `${a8}我是ME`.trim(); //使用 .trim() 可以消除反引號中的換行 數值的擴展
Number.parseInt(‘12.34‘) //12 取整 Number.parseFloat(‘12.34sdf‘) //12.34 只保留數字部分 Math.trunc(4.1) //4 去掉小數部分。只保留整數 Math.sign(-5) //-1 判斷是否正數還是負數 負數返回-1 正數返回 +1 Math.cbrt(2) //1.2599210498948734 計算數字的立方根 函數的擴展

function a9(b=0, c=1){}; //函數的參數中允許使用默認參數 替代了之前的 b = b || 0; function a10({x,y=5}){ console.log(x,y)} // a10({x:1,y:2}) 可以使用解構方式賦值 直接調用 並可以設置默認值 function a11({x,y=5} = {} ){ console.log(x,y)} //a11({y:2}) X 對象為undefined // 為了避免沒有默認值的參數報錯,所以給對象復制一個空對象 function a12(a,...b){ console.log(a+b[0]+b[1]) }(1,2,3); //6 rest參數 形式為...變量名 獲取函數的多余參數 rest是一個數組。和調用數組的方式一樣 a12.name //字符串返回函數的名字 var a13 = a=>a; //相當於 var a13 = function(a){return a} 箭頭函數 聲明 變量名 = 參數 => 返回值 如果函數體大於一條語句需要改為 =>{return a} //如果需要添加多個參數則需要加上() var a13 = (a,b) => a+b let a14 = ({ first, last }) => first + ‘ ‘ + last; //箭頭函數與變量解構結合使用 class的基本使用

class a15{ //創建class 類 constructor(x, y){ //類的默認屬性 this.x = x; this.y = y; this.h = "hello" } toString(){ //類中的方法。不需要寫function console.log(`${this.h}--${this.x+this.y}`) } b(){ //類中的方法。不需要寫function console.log(`world--${this.x+this.y}`) } static classMethod(){ //靜態方法,只能在本類調用。賦給其他表達式將找不到本方法 } } //new a15(1,2).toString(); class a16 extends a15{ //a16 類 將繼承a15類的所有方法 constructor(x,y){//定義類的默認屬性 super(x,y);//**調用父級的所有屬性和芳芳,此方法必須存在 this.c();//調用當前類的C方法。 } c(){ super.h="world2";//調用父級類的h屬性。調用父級方法時可以依然使用this調用,也可以使用super調用 this.toString();//調用父級類的toString()方法,方法中打印出來的h屬性被改變了 } } //var a18 = new a16(1,2) class a17 extends a16{ //a17 類 將繼承a16類和15類的所有方法的所有方法 constructor(x,y){//設置類的默認方法 super(x,y);//調用父級類(a16)。父級類中默認改變了a15類中的h屬性。所以在這裏也改變了 super.toString();//此方法調用的是父級類的父級類的方法。此方法中的變量被a16類改變後。在a17中調用a15類依然被改變了。 } } //new a17(13,22)

初入ES6隨筆