簡體   English   中英

Javascript-如何檢查變量之前未聲明

[英]Javascript - how to check variable is not declared before

我正在嘗試使用javascript加載圖像,首先獲得寬尺寸的圖像URL,然后當用戶打開moda時,我將加載寬尺寸的圖像。

我試圖用下面的方式做到這一點

try {
    images
}
catch(err) {
    if (err.name == "ReferenceError"){
        let images = [];
        let nodes = tab.childNodes[1].children;
        for (let i = 0; i < nodes.length; i++) {
            if (nodes[i].firstElementChild.className === "slider") {
                images.push(nodes[i].firstElementChild.src)
            }
        }
        Images:load(images)
    }
}

但這不起作用,每次都加載圖像。

我嘗試將這些代碼放在這些if語句中,但是它們都沒有起作用,它們給出了Uncaught ReferenceError: images is not defined at HTMLElement.<anonymous>錯誤

if (typeof images == 'undefined')

if (typeof images === undefined)

if (typeof images == 'undefined' || images.lenth === 0 )

有什么方法可以檢查之前未聲明的圖像變量?

使用以下代碼:

if (typeof variable !== 'undefined') {
    // variable is defined
}

GreatDharmatma是正確的。 檢查變量的類型是否嚴格等於“ undefined”將有助於解決您的問題。

if (typeof something !== 'undefined') {
    // do stuff when variable was declared
} else {
    // do stuff when variables was not declared
}

我還建議您看一下以下問題: 如何檢查JavaScript中未定義的變量

它對javascript中undefined ,未聲明的和null變量有很多解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM