如何以JavaScript獲取字串中命名全域性變數?


透過使用 alert(window()) 在警告中顯示。以下為語法 -

alert(window['yourVariableName' + 'yourVariableName' + otherVariableName]);

範例

 動態演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
   var globalVariablelocal_print100=100;
   print100=1;
   alert(window['globalVariable' + 'local_' + print100]);
</script>
</body>
</html>

如要執行以上程式,請儲存檔名anyName.html(index.html),然後在 VS 程式碼編輯器中右鍵單擊該檔案並選擇使用活動伺服器開啟選項。

輸出

更新於:16-Jul-2020

405 瀏覽數

開啟你的職業生涯

完成課程以獲得認證

開始學習
廣告