簡體   English   中英

如何檢查數組中的鍵是否存在而沒有錯誤代碼?

[英]How can I check if key in array exist without error code?

我故意使這個變量“generateError”不起作用,但是在檢查數組中的鍵時,我在另一個上下文中遇到了同樣的問題。 所以我的問題是,如何讓變量狀態只顯示“數組不工作”而不是生成錯誤代碼?

 var numbers = [1, 2, 3, 4]; var generateError = numbers['badKey'][2]; if (typeof(generateError)==undefined){ var status=("array not working"); } else { var status=("array is working"); } document.getElementById("status").innerHTML=status;
 <div id="status"></div>

var numbers = [1, 2, 3, 4];
var generateError = numbers['badKey'][2];
var status;
if (typeof(generateError)=='undefined'){
  status=("array not working");
} else {
  status=("array is working");
}

document.getElementById("status").innerHTML=status;

試試這個並閱讀這個頁面,它對你未來有幫助。

Side Info - typeof 方法將返回一個字符串,因此在使用它時嘗試這樣

if(typeof generateError == 'undefined')

您可以使用 try/catch 方法。 它將嘗試運行 try 塊中的所有內容,如果出現錯誤,catch 塊將捕獲錯誤並執行您想要的任何操作。

var numbers = [1, 2, 3, 4];
var status;

try{
    var tryToGetIndex = numbers['badKey'][2];
    status = tryToGetIndex;
}
catch(error){
    status="array is not working";
}

document.getElementById("status").innerHTML=status;

暫無
暫無

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

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