[英]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: 如果检查是在全局名称空间中进行的,我本可以使用
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 ...
});
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: 如果是这样,请使用
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"])
inside forEach
, each
loops over the variables 在
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.