如何检查JavaScript的定义和参数传递

How to check both defined and parameter passed with JavaScript?

本文关键字:定义 参数传递 JavaScript 何检查 检查      更新时间:2023-09-26

我有这个函数:

function(stringsVar) {
var stringRes = stringsVar || localize_en;
if('window.'+stringsVar === undefined) {
    stringRes = localize_en;
}
...
}

和不工作。实际上是这样的:

function(stringsVar) {
    var stringRes = stringsVar || localize_en;
}

函数可以接受或不接受形参,上面的代码正在正确地检查它。函数的参数是一个变量。我想把这种能力添加到我的函数中。它将检查该变量是否被定义。如果系统中没有定义变量localize_en,它将被作为默认值分配。

我如何纠正我的代码。我的代码的第二部分将是这个功能:例如stringsVar是localize_ar,它不是一个定义变量(我用var关键字定义了这种变量)

if(window.localize_ar === undefined){
alert('yes');}
else {
alert('no');
}

我将把这个功能添加为参数。

任何想法?

PS: localize_en之类的变量是object

编辑:我正在制作JQuery本地化插件=>源代码。我称之为

$('html').localize('localize_' + tr);

但是它不能把它理解为一个对象,它就像我一样工作:

$('html').localize(localize_tr);

它把它变成了一个字符串也许问题就在那里?

您可以使用方括号表示法来引用名称存储在变量中的对象成员,因此您可能要查找的是:

if (window[stringsVar] === undefined) {
}

进一步,||运算符将返回第一个真值;如果将对象作为第一个参数传递会发生什么?这是事实,但是您特别想要一个字符串,因此尽管||操作符看起来很酷,但您可能会发现以下操作符更合适:

if (typeof stringVar !== "string") {
    stringVar = "localize_en";
}

看起来你也很困惑,什么时候用字符串来引用你的目标对象,什么时候不用。

当你要做这样的事情时:

window[someVar]

someVar 要求为字符串。

在JavaScript中可以通过引用传递对象,在编写了上述所有内容以帮助您解决当前遇到的问题之后,更好的方法是首先通过引用传递对象,并完全避免问题,而不是传递名称存储对象的变量:

function(obj) {
    if (typeof obj !== "object") { 
        obj = localize_en; // here we're wanting the object itself, rather than the name of the object, so we're not using a string.
    };
    // Now use `obj`. It'll be either the object the user passed, or the default (localize_en).
    // You can even store this in a global variable if you want to:
    window.selected_obj = obj;
}

编辑:

从你的评论,试试这个:

function (stringsVar) {
    if (typeof stringsVar !== "string" || typeof window[stringsVar] !== "object") {
        stringsVar = "localize_en"; // Set the default of the argument, if either none is provided, or it isn't a string, or it doesn't point to a valid object
    }
    var stringRes = window[stringsVar];
    // Now do *whatever* you want with stringRes. It will either be the *valid* localization type the parameter specified, or the default ("localize_en").
}

你应该给这个函数传递一个字符串