簡體   English   中英

通過函數內部的字符串訪問變量

[英]Access variable by string inside function

我想檢查函數中提供的參數是否為字符串,為此,我使用以下條件:

function someFunction (variable1, variable2, variable3) {
   ["variable1", "variable2", "variable3"].forEach(function (each) {
      if (!(/*something*/[each].constructor.name === "String")) throw new TypeError(
         each + " must be a string. " + /*something*/[each].constructor.name +
         " was given instead."
      );
      else ...
   });
}

如果檢查是在全局名稱空間中進行的,我本可以使用window[each] ,因為變量是window屬性,如下所示:

var variable1, variable2, variable3;

["variable1", "variable2", "variable3"].forEach(function (each) {
   if (!(window[each] instanceof String)) throw new TypeError(
      each + " must be a string. " + window[each].constructor.name + " was given instead."
   );
   else ...
});

上面的功能如何實現?

您只想允許使用字符串,對不對? 如果是這樣,請使用arguments ,typeof和以下代碼:

function someFunction(variable1, variable2, variable3) {
    [].forEach.call(arguments, function(each) {
        console.log(typeof each);
        if (typeof each != 'string') {
            throw new TypeError(
                each + " must be a string. " + /*something*/ each.constructor.name +
                " was given instead."
            );
        } else {
            console.log("its a string")
        }
    });
}

someFunction("foo", "bar", ["baz"])

forEach內部, each循環遍歷變量

function someFunction (variable1, variable2, variable3) {
   [variable1, variable2, variable3].forEach(function (each) {
      if (!(each.constructor.name === "String")) throw new TypeError(
         each + " must be a string. " + each.constructor.name +
         " was given instead."
      );
      else ...
   });
}

暫無
暫無

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

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