在不赋值的情况下声明变量的目的?

时间:2017-01-24 14:55:03

标签: kentico

在不为其赋值的情况下声明变量的目的是什么?例如,我在文本/ XML转换中查看以下代码:

{%
    str1;
    bool1;
    bool2 = false;

    if (str1 != "something specific" && str1 != "") {
        bool1 = false;
        bool2 = true;
    }

    str1 = SomeFieldFromDataSource;

    return "";
#%}

{% if (bool1 != false) { return "<div>"; } #%}

{% if (bool2) { return "</div><div>"; } #%}

<div>Some content...</div>

前两个变量声明在做什么?他们只是将这些变量设置为某个默认值吗?如果不以某种方式声明类型,Kentico将如何知道要使用的值(除非它对所有内容使用单个默认值)?或者,前两个声明是否不必要?

我已经在互联网上搜索过了,但我没有在变量声明上看到太多,除非你不需要分配一个值,否则它不应该是必要的。但是,我不愿意开始删除部分代码,因为我对Kentico和转换语法都很陌生。

修改
为了增强对未分配变量的理解,我在转换中执行了以下测试,每个条件表达式的结果显示在右侧的注释中。

{% b; s; %} <!-- Evaluation of the following expressions is the same with or without this line. -->

{% if (b == true) { return "<div>b is true</div>" } #%}           <!-- false -->
{% if (b == false) { return "<div>b is false</div>" } #%}         <!-- false -->
{% if (b == null) { return "<div>b is null</div>" } #%}           <!-- true -->
{% if (b != true) { return "<div>b is not true</div>" } #%}       <!-- true -->
{% if (b != false) { return "<div>b is not false</div>" } #%}     <!-- true -->
{% if (b != null) { return "<div>b is not null</div>" } #%}       <!-- false -->

{% if (s == "") { return "<div>s is empty string</div>" } #%}     <!-- true -->
{% if (s == null) { return "<div>s is null</div>" } #%}           <!-- true -->
{% if (s != "") { return "<div>s is not empty string</div>" } #%} <!-- false -->
{% if (s != null) { return "<div>s is not null</div>" } #%}       <!-- false -->

总结一下,未分配的变量== null!= true!= false== ""。其中唯一可能令人惊讶的是最后一个== ""。但是,the documentation确实说明了这一点:

  

空字符串等于null

3 个答案:

答案 0 :(得分:1)

除了继承分配给它的数据的数据类型之外,没有其他目的。与JavaScript的工作方式非常相似。如果声明一个没有值的变量,它会假定一个对象。如果您指定一个字符串,它将是一个字符串。如果指定整数,则假定为整数。所以在这种情况下,对象可能是整数或字符串。无论哪种方式,当它被声明为良好的编码和阅读轻松时,应该给出一个值。

如果这是生产中的代码,我一定要优化它。但是不知道代码的完整上下文,或者如果在转换中有其他代码,我很难提供有效的示例。

<强>更新

根据您更新的代码,代码只会输出<div>Some content...</div>

由于每次呈现新项目时都会执行此代码,因此不会保留&#34; global&#34;像JS这样的价值可能会有所作为。您必须每次都将值分配给str1str2,然后执行一些逻辑检查。

答案 1 :(得分:1)

一般来说,省略声明是安全的。我认为代码的作者只是害怕初始化条件范围内的变量如果没有先声明它们就不会全局设置它们。事实并非如此。

但代码中的其他内容引起了我的注意。它是return "",它可能表示这段代码正在进行一些初步计算,其输出可能会在稍后的代码中使用。不要忘记可以像这样分开宏块:

// returns 2
{% return x + 2; %}

{% x = 1; %}

// returns 3
{% return x + 2; %}

或者像documentation中描述的那样:

// Displays a message including the current date if the year is 2014 or more
{% date = CurrentDateTime; if (date.Year > 2013) { %}
The current date is: {% date %}. The registration period has ended.
{% } %}

所以我肯定会在上述代码中寻找所有变量的进一步用法。

答案 2 :(得分:0)

在Kentico的K#中,所有项目都或多或少地存储为“对象”,而不是强类型,然后我相信它会通过获取该对象的类型来处理它。

这段代码来自哪里?它可能只是展示了如何做事的一个例子。你可以把你不需要的东西删掉,然后自己编写。