let不支持變量提高github
console.log(a); // 此處報錯 let a = "a";
let不能重複聲明數組
let a = "a"; let a = "abc"; // 報錯
let支持塊級做用域函數
if (true) { let a = "a"; } console.log(a) // 報錯 for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); // 0 1 2 3 4 }); }
const除了let的功能,還不能更改聲明後的值,不過能夠對聲明的對象增長屬性和更改屬性值rest
const PI = 3.14; PI = 3.141; // 報錯 const obj = { name: '小張' }; obj.name = '小紅'; obj.age = 25;
{ // 數組解構賦值 let [a, b, c] = [123, "abc", { name: "xiaohong" }]; console.log(a, b, c); // 123 'abc' { name: 'xiaohong' } } { // 對象解構賦值 let { name, age } = { name: "xiaohong", age: 25 }; console.log(name, age); // xiaohong 25 } { // 對解構賦值的值自定義名稱 let { name: myname, age: myage } = { name: "xiaohong", age: 25 }; console.log(myname, myage); // xiaohong 25 } { // 默認賦值,如果給age賦值將覆蓋默認值 let { name, age = 19 } = { name: "xiaohong" }; console.log(name, age); // xiaohong 19 } { // 省略賦值 let [, , a] = [1, 2, 3]; console.log(a); // 3 }
函數中使用展開運算符code
function test(a, b, c) {} let arr = [1, 2, 3]; test(...arr);
數組中函數中使用展開運算符對象
let [a, b, ...c] = [1, 2, 3, 4, 5]; console.log(a, b, c); // 1 2 [ 3, 4, 5 ] let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // [ 1, 2, 3, 4, 5 ]
類數組變量轉成數組ip
function test(a, b, c) { console.log([...arguments]); } test(1, 2, 4); // [1 2 4]
模板字符串:在這以前字符串拼接用+號來完成,如今用``和S{}便可代替字符串的拼接作用域
let name = 'xiaohong', age = 25; let str = `我叫:${name},今年${age}歲了`; console.log(str); // 我叫:xiaohong,今年25歲了 { // 自定義模板字符串的返回值 let name = "xiaohong", age = 25; // ...rest做爲參數只是放在最後 function desc(string, ...rest) { let str = ""; for (let i = 0, len = rest.length; i < len; i++) { str += string[i] + rest[i]; } str += string[string.length - 1]; return str.toLocaleUpperCase(); } let str = desc`我叫:${name},今年${age}歲了`; console.log(str); // 我叫:XIAOHONG,今年25歲了 }
判斷字符串以某個字符串開頭字符串
let str = "hello world!"; console.log(str.startsWith('h')); // true
判斷字符串以某個字符串結尾
let str = "hello world!"; console.log(str.endsWith('!')); // true
判斷字符創是否包含某個字符串
let str = "hello world!"; console.log(str.includes('hello')); // true
將字符串重複生成
let str = "hello world!"; console.log(str.repeat(3)); // hello world!hello world!hello world!