JavaScript: if let / if-scoped let



在JavaScript中的其他编程语言中,我似乎找不到任何类似于if let的东西。

如果我想得到堆栈溢出的徽标文本,我需要做

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但由于没有进一步的回应,我不知道是否已经有什么可以解决这个问题。

那么答案可能是使用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!

您不能在if中声明变量,但您可以很容易地进行赋值并检查它是否未定义:

let text, result;
if (text = document.querySelector('[class="-img _glyph"]')) {
result = text.innerText
//do some other work
} else {
result = "not found";
}

最新更新