我正在尝试修复代码,但我停在两行代码上,这些代码太奇怪了,我无法理解它们。所有行:
//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
:
检查变量url
和this.last_product_url
之间的严格相等性,并分配给f
。
f && productUrls.push(url)
:
如果f
true
,则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( }