第十三天前端浅记录

170 阅读1分钟

新的一天又开始了。今天老师会讲更现代的js。

逻辑运算符的扩展

  • || 直接上代码帮助理解。
const rest1 = {
    name: 'Capri',
    numGuests: 20
}

const rest2 = {
    name: 'La Piazza',
    owner: 'Giovanni Rossi'
}
rest1.numGuests = rest1.numGuests || 10;
rest2.numGuests = rest2.numGuests || 10;
console.log(rest1);
console.log(rest2);

输出结果

image.png

老师称这个为短路效果,说白了就是如果 || 前面值成立,则返回前面。否则就会返回后面的值。

还有更酷的事,打印前面的两行代码可以换成

rest1.numGuests ||= 10;
rest2.numGuests ||= 10;

这是不是看着和以前的+=看着很像? 其实道理也是类似的。

  • ?? 空赋值运算符
const rest1 = {
    name: 'Capri',
    numGuests: 0
}

const rest2 = {
    name: 'La Piazza',
    owner: 'Giovanni Rossi'
}
rest1.numGuests ??= 10;
rest2.numGuests ??= 10;

console.log(rest1);
console.log(rest2);

输出结果

image.png

它会返回一切数字,包括NaN。

  • &&
const rest1 = {
    name: 'Capri',
    numGuests: 0
}

const rest2 = {
    name: 'La Piazza',
    owner: 'Giovanni Rossi'
}

rest1.owner = rest1.owner && '<ANONYMOU>';
rest2.owner = rest2.owner && '<ANONYMOU>';

console.log(rest1);
console.log(rest2);

输出结果

image.png

&&前面的值如果存在,则会返回后面的,如果前面不存在,会返回undefined。

循环数组新方法(of)

const arr = ['a', 'b', 'c', 'd', 'e', 'f']
for (const item of arr.entries()) console.log(item);

输出结果

image.png

不难理解吧,entries()是数组的一个方法,会返回数组每一项的索引加value。

最近想戒烟了,有点心不在焉,今就到这了,好好歇一歇。