我似乎无法从if let的其他编程语言中找到类似于JavaScript的任何东西。
如果我想获得堆栈溢出的徽标文本,我需要这样做。
let text = document.querySelector('[class="-img _glyph"]')
if(text) {
result = text.innerText
//do some other work
}所以在声明之后,我必须先检查它是否是undefined,然后再使用它。现在,更符合逻辑的是以下内容:
if let text = document.querySelector('[class="-img _glyph"]') {
result = text.innerText
//do some other work
}然而,这在JavaScript中不起作用。我是否可以使用另一种语法来避免只对未定义的检查使用额外的行?
我找到了这个有10年历史的线程https://esdiscuss.org/topic/if-scoped-let,但是由于没有进一步的响应,我不知道是否已经有任何方法解决了这个问题。
发布于 2022-09-08 12:56:28
那么,答案可以是使用一个for循环:
for (let text = document.querySelector('[class="-img _glyph"]'); text; text = false) {
result = text.innerText;
console.log(result);
}
console.log("done");
或者--或者更符合可维护代码--您可以这样做。
{
let text = document.querySelector('[class="-img _glyph"]');
if (text) {
result = text.innerText;
console.log(result);
}
console.log("text:", text);
}
console.log(text) // will throw an error!
发布于 2022-09-08 14:01:32
您不能在if中声明变量,但可以执行赋值并检查它是否很容易定义:
let text, result;
if (text = document.querySelector('[class="-img _glyph"]')) {
result = text.innerText
//do some other work
} else {
result = "not found";
}https://stackoverflow.com/questions/73649284
复制相似问题