简体   繁体   中英

Access variable by string inside function

I want to check out whether the arguments provided in a function are strings and for this I'm using the following condition:

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 ...
   });
}

Had the check occurred in the global namespace, I could've used window[each] , since variables are properties of window , like below:

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 ...
});

How can the above be achieve inside a function?

You only want to allow strings, right? If so - use arguments , typeof and the code below:

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"])

inside forEach , each loops over the variables

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 ...
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM