javascript - php "||"赋值逻辑与Javascript对比

标签 javascript php variable-assignment

我正在测试 Heredoc 和 ||功能

function test()
{
    $obj = [(object)['col1'=>'val1'],
            (object)['col2'=>'val2'],
            (object)['col3'=>'val3']];
    $output = '';
$mystring = <<<EOT
a non empty string
EOT;

    foreach($obj as $prop)
    {
        foreach($prop as $i)
        {
            $output .= <<<EOT
            <div style='background-color:lightblue'> 
            \$head  : {gettype($i)} 
            </div>
EOT;
        }
    }
    $out =  $output || $mystring || 'couldn\'t find something valuable';
    echo $out;
}
test();

我得到了

的输出

1

表示 bool 值 true。 我通过将逻辑放在括号中使其在某一时刻输出 $mystring 的内容,例如

echo ($output || $mystring);

它曾经输出:

a non empty string

它立即停止工作,我不确定是什么改变破坏了它。

在 JavaScript 中:

    function test()
    {
    
        var obj = [{'col1':'val1'},
                {'col2':'val2'},
                {'col3':'val3'}];
        var output = '';
        var mystring ="a non empty string";
    
        for(var prop in obj)
        {
            for(var i in prop)
            {
                output += 
                "<div style='background-color:lightblue'>" +
                    i + " : " + typeof prop[i] +
                    "</div>";
            }
        }
        out =  output || mystring || 'couldn\'t find something valuable';
        document.write(out);
        console.log("outputting \n\t" + out);
    }
    test();

它在逻辑上与 php 略有不同,但 ||在分配期间按预期工作。我明白了

0 : string

0 : string

0 : string

对于上面的代码。如果像这样注释掉内部 for 循环

for(var prop in obj)
{
    /*for(var i in prop)
    {
        output += 
        "<div style='background-color:lightblue'>" +
        i + " : " + typeof prop[i] +
        "</div>";
    }*/
}

我得到“mystring”的内容是

a non empty string

然后如果我像这样将 mystring 更改为空字符串

mystring = ""; //"a non empty string";

我明白了

couldn't find something valuable

php的“||”是如何实现的在分配工作期间? 谁能解释一下?

最佳答案

如果你在 php 中分配一个条件表达式,你总是得到一个 bool 值(即严格的 truefalse),它不像在 javascript 中那样工作,其中 "truthy"值被赋值,所以在 PHP 中

$a = "";
$b = 42;
$c = ($a || $b); // == true

在 javascript 中

var a = "";
var b = 42;
var c = (a || b); // == 42

遗憾的是,这是语言设计造成的。

正如@billyonecas 报道的那样,它也在对文档的评论中:http://php.net/manual/en/language.operators.logical.php#77411

要在 PHP 中获得类似的行为,我们必须做类似的事情:

$a = "";
$b = 42;
$c = ($a ?: $b); // newer php version
$c = ($a ? $a : $b); // older php version

如果您需要连接表达式,请使用括号:

$c = ($a ? $a : ($b ? $b : "not found"));

关于javascript - php "||"赋值逻辑与Javascript对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30234920/

相关文章:

javascript - Snap.svg:如何使用Set.bind(...)?

php - 外循环只触发一次

php - 菜单页面状态

java - 如何以独特的方式分配变量以求减法中的补数

java - 为什么一些开发人员以这种方式分配原始整数?整数 i = 0x0001

javascript - 防止通过检查元素下载html5视频

javascript - ES6 模块 : How to automatically re-export all types in the current directory from index. js?

javascript - 使用垂直框的 Twitter 关注者计数

c - 为字符串分配新值 - C

java - Base64 解码无法与 Android 中的 Cipher.Decrypt 一起正常工作