let&const
let不支撑变量提拔
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的功用,还不能变动声明后的值,不过可以对声明的对象增添属性和变动属性值
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
}
睁开运算符
函数中运用睁开运算符
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 ]
类数组变量转成数组
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!