节点 js.如何理解 s1 = s2 === s3 和 s1 && s2?



我正在尝试修复代码,但我停在两行代码上,这些代码太奇怪了,我无法理解它们。所有行:

//Extraction of urls
let f = !this.last_product_url
for(const productLink of productLinks) {
const url = await productLink.getAttribute('href')
if(!f) {
f = url === this.last_product_url
f && productUrls.push(url)
}
else {
productUrls.push(url)
}
}

这两行有什么作用:

f = url === this.last_product_url
f && productUrls.push(url)

f = url === this.last_product_url会将url === this.last_product_url的结果分配给f。

f && productUrls.push(url( 与下面相同:

if(f) productUrls.push(url)

语法上,这是发生的事情:

f = url === this.last_product_url

检查变量urlthis.last_product_url之间的严格相等性,并分配给f

<小时 />

f && productUrls.push(url)

如果ftrue,则url推送到productUrls

其工作原理如下。语句A && B被计算,但只有在A为真时才检查B,因为如果A为假,则A && B永远不会为真。因此,如果A为 true,则检查B:推送 url。

这两行正在做

f = (url === this.last_product_url);
if (f) {
productUrls.push(url);
}

循环体可以通过写作来澄清

let f = !this.last_product_url;
for (const productLink of productLinks) {
const url = await productLink.getAttribute('href')
if (!f) {
f = (url === this.last_product_url);
}
if (f) {
productUrls.push(url);
}
}

但是这个奇怪的f标志真正做的是从productLinks之后获取所有网址url === this.last_product_url.所以整个事情可能应该写成

const allProductUrls = await Promise.all(productLinks.map(productLink =>
productlink.getAttribute('href');
));
const lastIndex = this.last_product_url 
? allProductUrls.indexOf(this.last_product_url)
: 0;
if (lastIndex > -1) {
productUrls.push(...allProductUrls.slice(lastIndex));
}
f = url === this.last_product_url
f && productUrls.push(url)

这两行代码是表示以下逻辑的紧凑方式:

if(url === this.last_product_url){
productUrls.push(url);
}

f = url === this.last_product_url等效于

if (url === this.last_product_url) {
f = true;
} else {
f = false;
}

f && productUrls.push(url)相当于

if (f) {
productUrls.push(url)
}

f = url === this.last_product_url ->f = (url === this.last_product_url( -> 根据 url 和this.last_product_url比较返回布尔值

f && productUrls.push(url( ->推送函数仅在 f 为真时调用 -> if(f( { productUrls.push(url( }

相关内容

最新更新