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!