![](/img/trans.png)
[英]How to access variables inside function based on string variable representation
[英]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.