javascript:定义一个变量,如果不存在的话

问题描述 投票:54回答:13

我觉得我试图做一些超级简单的事情,但只是对此感到愚蠢。

我要做的就是查看变量是否已预先设置,如果尚未设置,则将其设置为默认值。...以下是示例:

if(!embed_BackgroundColor) {
    var embed_BackgroundColor;
    embed_BackgroundColor = "#F4F4F4";
}

所以,一旦您停止嘲笑我的代码。...为什么无论如何都会覆盖变量?

请保存我的神经;)

javascript variables
13个回答
60
投票
if (typeof variable === 'undefined') {
    // variable is undefined
    // eg:
    // var variable = "someValue";
}

0
投票
[我关注Chris West的博客,发现他在http://gotochriswest.com/blog/2012/07/02/javascript-define-if-undefined/上发布了一种非常酷的方法。

基本上,您已经定义了define函数,然后像这样使用它:


0
投票
因为如果ifembed_BackgroundColorfalse0""nullundefined,则将执行NaN块。

但是,如果embed_BackgroundColor已被分配给另一个

非空字符串


0
投票
最佳选择:

if (typeof someVar === 'undefined') someVar = someValue;


0
投票
if(embed_BackgroundColor ==“”){}

78
投票

专业风格:

var SomeVar = SomeVar || 'Default Value';

49
投票

在这种情况下,使用三元运算符将是一种很好的编码实践。此外,与typeof进行比较时,您不需要具有三个等号。这是最简洁的解决方案:

b = typeof(b) == 'undefined' ? 0 : b;

希望这可以节省您的时间。


29
投票

实际上要回答您为什么会这样的问题-仅仅两年多了一个月才:D-,这是因为variable hoisting

[基本上,在全局范围内或函数内部执行代码之前有一个阶段,在该阶段中扫描所有varfunction声明的代码(不要与函数expressions]混淆,但这是一个不同的故事)。然后,所有这些变量和函数都在当前作用域内声明,并且only afterafter才真正运行代码。

无论它们在代码中的位置如何,都将发生这种情况,作用域对应于函数体,而不是语句块。即使您在变量的声明they will still remain "empty" until the declaration is reached again in normal execution flow中将初始值设置为变量,这也使这更加违反直觉。

所以当你写:

if(!embed_BackgroundColor) {
    var embed_BackgroundColor;
    embed_BackgroundColor = "#F4F4F4";
}

实际发生的事情是这样:

  1. 将扫描代码以查找var声明。不论是否已声明,都在此范围内声明embed_BackgroundColor。其初始值是不确定的。

  • 代码开始执行。 if语句运行。声明了变量[[is

    ,但其值未定义,因此条件为true。使用typeof并不能帮助您在这里区分未声明变量和已声明但尚未设置的变量。无论如何都没什么区别。
  • var声明通过正常的代码流到达。如果为变量提供了一个初始值,那么现在就可以对其进行设置。在这种情况下,什么也不会发生。
  • [embed_BackgroundColor被设置为值"#F4F4F4"
  • 因此,最重要的是:您可以使用其他答案中所示的typeof variable == 'undefined',甚至可以像最初使用时那样使用普通的'!variable',但不要使用var,否则将破坏所有内容。] >

    我更喜欢这种语法:

    embed_BackgroundColor = embed_BackgroundColor || "#F4F4F4"

    没有比这更简单的了!即使它已经变了,它似乎也可以工作。

    如果是全局变量,我喜欢这样做:

    var defineMe = window.defineMe || 'I will define you now';

    使用窗口名称空间很重要,因为引用未定义的变量将导致非常严重的错误,但是引用未定义的属性则不会。

    如果embed_BackgroundColor是未传递的函数中的参数,则可以使用设置默认值

    embed_BackgroundColor ? embedBackgroundColor : embed_BackgroundColor = "#F4F4F4";

    全功能示例

    function colorFunctionThing(embed_BackgroundColor) { embed_BackgroundColor ? embed_BackgroundColor : embed_BackgroundColor = "#F4F4F4"; console.log(embed_BackgroundColor); }; colorFunctionThing();

    输出

    #F4F4F4

    不完全是您要找的东西,但仍然非常了解。

    我认为您发布的代码应该有效。除非您的原始值为0。

    问题出在其他地方。

    我猜您在代码范围之外定义了'embed_BackgroundColor'。而且,当您运行代码时,该变量在代码范围内是未定义的,并将被分配默认值。

    这里是一个例子:

    var embed_BackgroundColor = "#FF0000"; (function(){ if(!embed_BackgroundColor) { var embed_BackgroundColor; embed_BackgroundColor = "#F4F4F4"; } alert(embed_BackgroundColor); // will give you #F4F4F4 })(); alert(embed_BackgroundColor); // will give you #FF0000;

    我更喜欢采用类似PHP风格的通用解决方案:

    function isset(x) { return typeof(x)!='undefined'; }

    [我关注Chris West的博客,发现他在http://gotochriswest.com/blog/2012/07/02/javascript-define-if-undefined/上发布了一种非常酷的方法。

    基本上,您已经定义了define函数,然后像这样使用它:

    define("embed_BackgroundColor", "#F4F4F4");

    如果上面的代码尚未定义,则它将在全局上下文中定义enbed_BackgroundColor。克里斯使用的示例更加有用,如下所示:

    alert("jStuff is " + (typeof jStuff == "undefined" ? "un" : "") + "defined."); define("jStuff.alert", function(msg) { alert(msg); return msg; }); alert("jStuff is " + (typeof jStuff == "undefined" ? "un" : "") + "defined."); var str = jStuff.alert("Show and save this message.");

      第一条警告语句将显示,“ jStuff未定义。”
    • 第二个警报语句将显示“ jStuff已定义。”
    • 最终警报语句将显示指定的警报,然后该字符串将存储在str变量中。
    • 因为如果ifembed_BackgroundColorfalse0""nullundefined,则将执行NaN块。

      但是,如果embed_BackgroundColor已被分配给另一个

      非空字符串

      ...,或者至少在我这端,它不应该被覆盖。
      也许这是范围冲突的情况,正如钱亚伦指出的。

      最佳选择:

      if (typeof someVar === 'undefined') someVar = someValue;

      if(embed_BackgroundColor ==“”){}

    11
    投票
    我更喜欢这种语法:

    embed_BackgroundColor = embed_BackgroundColor || "#F4F4F4"


    10
    投票
    如果是全局变量,我喜欢这样做:

    var defineMe = window.defineMe || 'I will define you now';


    1
    投票
    如果embed_BackgroundColor是未传递的函数中的参数,则可以使用设置默认值

    embed_BackgroundColor ? embedBackgroundColor : embed_BackgroundColor = "#F4F4F4";


    0
    投票
    我认为您发布的代码应该有效。除非您的原始值为0。

    问题出在其他地方。


    0
    投票
    我更喜欢采用类似PHP风格的通用解决方案:

    function isset(x) { return typeof(x)!='undefined'; }

    © www.soinside.com 2019 - 2024. All rights reserved.