簡體   English   中英

如果您在javascript中有字符串,如何檢查變量是否已定義?

[英]How to check if a variable is defined if you have a string of it in javascript?

我知道如果您要檢查是否定義了變量a ,可以執行此操作

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

但是,如果您想以此來實現功能,該怎么辦?

function checkDefined(name) {
    return typeof name !== 'undefined';
}
checkDefined("a");

這是行不通的,但是如果我必須傳遞變量名的字符串版本的話,如何使它工作?

謝謝

檢查全局范圍(窗口):

 var a = 'test'; var b = function() {}; function checkDefined(name) { return typeof this[name] !== 'undefined'; } console.log(checkDefined("a")); console.log(checkDefined("b")); console.log(checkDefined("c")); 

如果要檢查是否在類對象中聲明了變量或函數,則應將新的上下文傳遞給checkDefined方法:

  function MyCustomClass() { this.c = 'test'; } function checkDefined(name) { return typeof this[name] !== 'undefined'; } // Create new object of type MyCustomClass var myCustomClassObject = new MyCustomClass(); // In this way you can check if variable/function is defined in object console.log(checkDefined.apply(myCustomClassObject, ["a"])); console.log(checkDefined.apply(myCustomClassObject, ["b"])); console.log(checkDefined.apply(myCustomClassObject, ["c"])); 

apply將立即調用一個函數,讓您同時指定this的值和該函數將接收的任何參數

受到這個答案的啟發。 我認為您可以嘗試使用eval返回:

function checkDefined(name) {
  return eval("typeof " + name) !== 'undefined';
}

例:

var a = 1;

checkDefined("a") // true
checkDefined(a) // true
checkDefined("b") // false

您還應該傳遞需要檢查哪個對象上下文,以確定變量是否已定義。 如果是全局,則通過window對象

function checkDefined(name, ref) {
    if(!ref) {
      ref = window;
    }
    return !!ref[name]
}


checkDefined("a"); //false if already not defined


var obj = { a: 1, b:2};
checkDefined("a",obj);//true

局部變量是當前作用域this對象的屬性。

 const log = output => document.querySelector('pre') .innerText += output + '\\n' /* In this example, running in the browser, `this` points to `window`, but in other environments would still point to whatever is the global object. Bind `this` to the ``checkDefined` so to ensure it keeps the same value as where you are calling from. */ const checkDefined = function chkDef(v) { return typeof this[v] !== 'undefined' }.bind(this) a = 5 log(checkDefined('a')) log(checkDefined('b')) /* This is the same basic idea, but we make it a little more portable by not binding until right before we use it, so `this` has the correct scope. */ unboundCheckDefined = function chkDef(v) { return typeof this[v] !== 'undefined' } newScope() function newScope() { c = 5 const checkDefined = unboundCheckDefined.bind(this) log(checkDefined('a')) log(checkDefined('b')) log(checkDefined('c')) } 
 <pre></pre> 

暫無
暫無

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

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