- 1. Destructuring Arrays 解构数组
- 2. Destructing Objects 解析对象
- 3. The Spread Operator 传播运算符
- 4. Rest pattern and Parameters
- 5. Short Circuiting(&& and ||)
- 6. The Nullish coalescing operator(??)
- 7. Logical Assignment Operators
- 8. Coding Challenge 1
- 9. Looping Arrays The for-of loop
- 10. Enhanced Object Literals 增强的对象字面值
- 11. Optional chaining 可选链接
Data Structures, Modern Operators and Strings
基础的语法,基础的Javascript功能
1. Destructuring Arrays 解构数组
destructing is an ES6 feature
and it’s basically a way of unpacking values 实际上就是一种给值解包的方式
from an array or an object into seperatate variables. 把数组或者对象拆分成单独的变量
把数组或者对象解包成单独的值
destructing is to break a complex data structure down
into a smaller data structure like a variable
解析就是把复杂的结构【数组、对象】分解为简单的结构【变量】
解析数组
const arr = [2, 3, 4];
// 之前的检索数组的方式
const a = arr[0];
const b = arr[1];
const c = arr[2];
console.log(a, b, c);
// 解析的方式
const [x, y, z] = arr; //看起来是数组,其实是完成解析任务;所以看到 [] = 就是在解析; 不要忘记使用 const 声明变量
console.log(x, y, z);
取变量
// 按照顺序取出变量
console.log(restaurant.categories);
const [first, second] = restaurant.categories;
console.log(first, second);
// 取出第一个和第三个
const [first1, , third] = restaurant.categories;
console.log(first1, third);
交换变量
//交换变量
console.log('------switching variables------');
let [main, , secondary] = restaurant.categories;
console.log(main, secondary);
// 之前交换变量的方式
// const temp = main;
// main = secondary;
// secondary = temp;
// console.log(main, secondary);
// 使用 解析的方式
[main, secondary] = [secondary, main];
console.log(main, secondary);
解析函数返回的数组
...
order: function (starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
},
...
//解析 函数返回的数组
console.log('------constructing the array from function------');
const [starter, mainM] = restaurant.order(0, 2);
console.log(starter, mainM);
嵌套的数组
// 嵌套的数组 nested array
console.log('------nested array------');
const nested = [2, 4, [5, 6]];
const [i, , j] = nested;
console.log(i, j);
//在解析里面继续解析
const [o, , [p, q]] = nested;
console.log(o, p, q);
默认值
// 设置默认值
console.log('------default values------');
// const [r, s, t] = [8, 9]; //8 9 undefined
const [r = 1, s = 1, t = 1] = [8, 9];
console.log(r, s, t);
2. Destructing Objects 解析对象
解析对象
// 解析对象, 不需要注意【顺序】,只要 【属性名称】 对就行
console.log('------ destructing objects ------');
const { restaurant_name, openingHours, categories } = restaurant;
console.log(restaurant_name, openingHours, categories);
给属性重命名
console.log('------ rename property ------');
const {
restaurant_name: restaurant_Name,
openingHours: hours,
categories: tags,
} = restaurant;
console.log(restaurant_Name, hours, tags);
默认值
// 默认值,当要读取的对象属性不存在时候,很重要
console.log('------ default value ------');
// const { menu, starterMenu: starters = [] } = restaurant; //undefined
const { menu = [], starterMenu: starters = [] } = restaurant;
console.log(menu, starters);
mutating variable
// mutating variables 改变变量
// {} 是代码块不能直接赋值操作 要加 ()
console.log('------ mutating variables ------');
let a = 1;
let b = 1;
const obj = { a: 28, b: 39, c: 12 };
({ a, b } = obj);
console.log(a, b);
嵌套对象
// nested objects 嵌套的对象
console.log('------ nested objects ------');
const { fri } = restaurant.openingHours;
console.log(fri);
const {
fri: { open: o, close: c },
} = restaurant.openingHours;
console.log(o, c);
对象作为函数参数
...
orderDelivery: function ({
starterIndex = 1,
mainIndex = 0,
time = '20:00',
address,
}) {
console.log(
`Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delived to ${address} at ${time}`
);
}
...
restaurant.orderDelivery({
time: '22:30',
addrss: 'NY',
mainIndex: '2',
starterIndex: '2',
});
3. The Spread Operator 传播运算符
扩展数组
// 扩展数组
const arr = [7, 8, 9];
const badNewArr = [1, 2, arr[0], arr[1], arr[2]];
console.log(badNewArr);
const newArr = [1, 2, arr];
console.log(newArr);
const newArr1 = [1, 2, ...arr];
console.log(newArr1);
数组扩展
//扩展数组
const newMenu = [...restaurant.mainMenu, 'Gnocci'];
console.log(newMenu);
复制数组
// 复制数组 这是浅拷贝
console.log('------ copy array ------');
const mainMenuCopy = [...restaurant.mainMenu];
console.log(mainMenuCopy);
连接两个数组
// 连接两个数组
const mainMenuJoint = [...restaurant.mainMenu, ...restaurant.mainMenu];
console.log(mainMenuJoint);
作用于Iterables
// Iterables: arrays, strings, sets, maps, NOT objects
console.log('------ Iterables ------');
const str = 'Jonas';
const letters = [...str, ' ', 'S.'];
console.log(letters);
console.log(...str);
//console.log(`${...str} Schmdtman`);
spread operator works on all so-called iterables
应用于所有可迭代对象
array, string, set, map, NOT object
console.log(`${...str} Schmdtman`);
在函数传参时候使用
...
orderPasta: function (ing1, ing2, ing3) {
console.log(`you get a pasta with ${ing1}, ${ing2} and ${ing3}`);
},
...
// 扩展操作符在函数传参时候使用
console.log('------ 扩展操作符在函数传参时候使用 ------');
const ingredients = [
prompt("Let's make pasta! Ingredient 1?"),
prompt('Ingredient 2?'),
prompt('Ingredient 3'),
];
console.log(ingredients);
restaurant.orderPasta(ingredients[0], ingredients[1], ingredients[2]);
restaurant.orderPasta(...ingredients);
使用在object上
ES2018 后可以使用在了 object
// Object
const newRestaurant = { foundedIn: 1998, ...restaurant, foounder: 'Mark' };
console.log(newRestaurant);
4. Rest pattern and Parameters
与 spread operator 相反
unpack an array
pack elements into an array
put the rest elments packed into an array
// spread, because on the Right
const arr = [1, 2, ...[3, 4]];
// rest, because on the left
const [a, b, ...others] = [1, 2, 3, 4, 5];
console.log(a, b, others);
/// functions
console.log('------ add function ------');
const add = function (...numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
};
add(2, 3);
add(1, 2, 3, 4, 5);
const x = [2, 4, 6, 8];
add(...x);
5. Short Circuiting(&& and ||)
AND | && | |
---|---|---|
OR | || | 如果第一个是true的值,就返回这个值,不进行后面的操作; 如果第一个不是,往后找,找到为true的值,返回这个值,然后不再进行后面的操作 |
// use ANY data type, return ANY data type, short-circuiting
console.log(3 || 'Jonas');
console.log('' || 'Mark');
console.log(true || 0);
console.log(undefined || null);
console.log(undefined || 0 || '' || 'hello' || 23 || null);
console.log(0 && 'Jonas');
console.log(7 && 'Jonas');
console.log('hello' && 'Jonas' && 'there' && null);
6. The Nullish coalescing operator(??)
ES 2020
nullish :
null and undefine
NOT 0 or ‘’
7. Logical Assignment Operators
const rest1 = {
name: 'Capi',
numGuests: 20,
};
const rest2 = {
name: 'La Piazza',
owner: 'Mark',
};
// OR assignment operator
// rest1.numGuests = rest1.numGuests || 10;
// rest2.numGuests = rest2.numGuests || 10;
rest1.numGuests ||= 10;
rest2.numGuests ||= 10;
console.log(rest1);
console.log(rest2);
但是 如果 rest1.numGuests = 0 , || 会把 0 判断为false
rest1.numGuests ??= 10;
rest2.numGuests ??= 10;
8. Coding Challenge 1
9. Looping Arrays The for-of loop
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
console.log(menu);
for (const item of menu) {
console.log(item);
}
for (const item of menu.entries()) {
console.log(item);
}
看看 menu.entries() 是什么
是一个数组迭代器
console.log(menu.entries()); //Array Iterator {}
什么是数组迭代器,展开看一看
是7个数组,每个数组有两个元素,一个索引号,一个值
console.log([...menu.entries()]);
item 本身是一个数组,所以可以用spread array 分别得到 索引号和值
for (const [index, element] of menu.entries()) {
console.log(`${index}: ${element}`);
}