Javascript - 4
Javascript - 4
解构数组
const arr = [2, 3, 4];
const [x,y,z] = arr; // 2,3,4
const[first, second] = arr;
console.log(first, second); // 2,3
const[first, , second] = arr;
console.log(first, second); // 2,4
const nested = [2, 4, [5,6]];
const [i, ,[j,k]] = nested;
console.log(i,j,k); // 2,5,6
交换变量
// 交换(不需要临时变量)
[first, second] = [second, first];
console.log(first, second); // 4,2
Recieve 2 return values from
const restaurant = {
starter: ['Focaccia','Bruschetta','Garlic Bread'],
main: ['Pizza','Pasta'],
order: function(starterIndex, mainIndex){
return [this.starter[starterIndex], this.main[mainIndex]]
},
}
const [starter, main] = restaurant.order(2,0);
设置解构的默认值
在不知道数组的长度时很有用
const[p=1, q=1, r=1] = [8, 9];
console.log(p,q,r); // 8,9,1
解构对象
对象中的元素顺序不重要,所以不需要像结构数组一样手动跳过
const restaurant = {
name: 'Classic Italiano',
starter: ['Focaccia','Bruschetta','Garlic Bread'],
main: ['Pizza','Pasta'],
order: function(starterIndex, mainIndex){
return [this.starter[starterIndex], this.main[mainIndex]]
},
openingHours: {
thu:{
open: 12,
close: 22,
},
fri:{
open: 11,
close: 23,
},
sat:{
open: 0,
close: 24,
},
},
// 立即解构
orderDelivery: function({starter = 1, main = 0, time = '20:00'}){
console.log('');
}
};
const {name, openingHous, starter} = restaurant; // 必须指定属性的名称
// 给新的变量名
const {name: restaurant, openingHous: hours, starter: starters} = restaurant;
console.log(restaurant, hours, dishes);
// 设置默认值
const {menu=[], starter: starters=[]} = restaurant;
let a = 111;
let b = 999;
const obj = {a:23, b:7, c:14};
({a,b} = obj); // 解构赋值需要包裹在括号 () 中,否则会被解析为代码块
// 嵌套对象
const {fri:{open, close}} = openingHours;
console.log(open,close); // 11,23
// 立即解构
restaurant.orderDelivery({
time: '22:30',
main:2,
starter:2,
});
展开运算符 the spread operator
- 浅拷贝
- 适用于所有可迭代对象(数组、字符串、映射、集合,ES2018后对象也可以。即使对象不是可迭代的)
- 用在 可以用多个逗号分隔 的 写值的地方(创建新数组、传递函数参数)
展开数组
从数组中取出所有元素,自动地写到相应位置
const arr = [7,8,9];
const newArr = [1,2, ...arr];
console.log(newArr); // [1,2,7,8,9]
传参给函数
当写了一个数组,需要将数组中的元素传递到一个函数时
// 将数组变为单个元素
console.log(...newArr); // 1,2,7,8,9
展开字符串
const str = 'Jonas';
const letters = [...str, ' ', '.S'];
console.log(letters); // ["J","o","n","a","s"," ",".S"]
console.log(...str); // J o n a s
不能用在 模式字符串
展开对象
const newRestaurant = { foundedIn: 1998, ...restaurant, founder: 'Guiseppe'};
Rest Pattern
- 用在 可以用多个逗号分隔 的 写变量名的地方
数组
收集其余的元素,压缩成一个数组
// SPREAD, on RIGHT side of =
const arr = [1,2, ...[3,4]];
// REST, on LEFT side of =
const [a, b, ...otherts] = [1,2,3,4,5];
console.log(a,b,others); // 1 2 [3,4,5]
rest 收集 最后一个变量之后的所有元素,不包括被跳过的元素(rest element 必须是最后一个元素,且只能有一个)
const [pizza, , risotto, ...otherFood] = [
...restaurant.mainMenu,
...restaurant.starterMenu,
]
对象
收集其余的属性到新对象中
const {sat, ...weekdays} = restaurant.openingHours;
函数 - Rest arguements
const add = function(...numbers){
console.log(numbers);
};
add(2, 3); // [2,3]
add(3, 4, 5); // [3,4,5]
短路
使用任何数据类型,返回任何数据类型
OR ||
// 第一个值是 truthy value,直接返回第一个值,不评估后面的操作数
console.log(3 || 'Jonas'); // 3
console.log(true || 0); // true
console.log('' || 'Jonas'); // Jonas
// 全是 falsy value 返回最后一个 falsy value
console.log(undefined || null); // null
// 返回第一个 truthy value
console.log(undefined || 0 || '' || 'Hello' || 23 || null);
- 使用 空值合并符
??
左侧的值为 null 或 undefined 时,才会使用右侧的默认值
restaurant.numGuest = 23;
const guests = restaurant.numGuest || 10; // 当客人数为0的时候不行
// 解决方法
const guests2 = restaurant.numGuest ?? 10;// 使用 nullish value无效值的概念,而不是 falsy value
nullish value:null, undefined (NOT 0 or '')
AND &&
// 第一个值是 falsy value,直接返回第一个值,不评估后面的操作数
console.log(0 || 'Jonas'); // 0
// 全是 truthy value 返回最后一个 truthy value
console.log(7 || 'Jonas'); // null
// 返回第一个 falsy value
console.log('Hello' && 23 && null && 'Jonas'); // null
- 使用
restaurant.orderPizza && restaurant.orderPizza('mushrooms');
简洁的方式
||=, ??=, &&=
遍历数组 for of 循环
获取元素
continue break 任然可以使用
// 获取当前元素
for(const item of menu) console.log(item); // item 是元素
获取索引
// 获取当前索引
for(const item of menu.entries()) console.log(item); // item 是数组 [index,"element"]
menu.entries() 是 Array Iterator,该 数组 的每一项都是 [index,"element"] 的数组
object literals 对象字面量
- 对象
- 函数
const openingHours = {
thu:{
open: 12,
close: 22,
},
fri:{
open: 11,
close: 23,
},
sat:{
open: 0,
close: 24,
},
};
const restaurant = {
name: 'Classic Italiano',
starter: ['Focaccia','Bruschetta','Garlic Bread'],
main: ['Pizza','Pasta'],
order: function(starterIndex, mainIndex){
return [this.starter[starterIndex], this.main[mainIndex]]
},
// 1.
openingHours, // 等价于 openingHours: openingHours,
// 2. 直接设置函数
greet() {
console.log(`Hello, this is ${this.name}`);
}
};
- 计算属性
使用变量名作为属性名,要使用 []
const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
const openingHours = {
[weekdays[3]]:{
open: 12,
close: 22,
},
[weekdays[4]]:{
open: 11,
close: 23,
},
[weekdays[5]]:{
open: 0,
close: 24,
},
};
Optional Chaining 可选链操作符
ES2020(11)
- 属性
如果某个属性不存在,就会立即返回 undefined,而不是报错
console.log(restaurant.openingHours?.mon?.open);
for(const day of weekdays){
console.log(restaurant.openingHours[day]?.open ?? "closed");
}
- 方法
如果某个方法不存在,就会立即返回 undefined,而不是报错
console.log(restaurant.order?.(0,1) ?? 'Method does not exit');
- 数组
const users = [{name: 'Jonas', email: 'hello@jonas.io'}];
console.log(users[0]?.name ?? 'User array empty');
遍历对象
对象默认不可遍历,可以使用 Object.keys(), Object.values(), Object.entries() 来获取对象的键、值或键值对数组
遍历属性名 (Key)
for(const day of Object.keys(openingHours)){
console.log(day);
}
Object.keys() 返回 元素是 属性名 的数组 ["key1","key2"]
遍历属性值 (Value)
for(const values of Object.values(openingHours)){
console.log(values);
}
Object.values() 返回 元素是 属性值 的数组
遍历条目 (Entries)
for(const x of Object.entries(openingHours)){
console.log(x);
}
Object.entries() 返回 元素是 ["key", value] 的数组

浙公网安备 33010602011771号