通过函数内的字符串访问变量

时间:2016-08-30 18:09:32

标签: javascript

我想检查一个函数中提供的参数是否是字符串,为此我使用以下条件:

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

如何在功能内实现上述目标?

2 个答案:

答案 0 :(得分:1)

你只想允许字符串,对吗?如果是这样 - 请使用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"])

答案 1 :(得分:1)

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