PHP 和 JS 变量求值的区别
有人可以向我解释一下为什么下面的 JavaScript 代码会生成 321 警报,而 PHP 代码会生成 1。
我知道 PHP 代码会计算表达式并返回 true 或 false。我不知道为什么在 JavaScript 中它像三元运算符一样工作。这只是语言中实现事物的方式吗?
var something = false; var somethingelse = (something || 321); alert(somethingelse); // alerts 321
$var = '123'; $other = ($var || 321); echo $other; // prints 1
谢谢!
Can someone please explain to me why the following javascript code produces an alert with 321 and the PHP code produces 1.
I know the PHP code evaluates the expression and returns true or false. What I don't know is why in JavaScript it works like a ternary operator. Is it just the way things were implemented in the language?
var something = false; var somethingelse = (something || 321); alert(somethingelse); // alerts 321
$var = '123'; $other = ($var || 321); echo $other; // prints 1
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,JavaScript 的做法有点不同。表达式
(something || 321)
表示something
是否属于 falsy 值,使用默认值321
代替。在条件表达式中,
||
像往常一样充当逻辑OR
,但实际上它执行相同的合并操作。您可以使用以下代码对此进行测试:在 PHP 中,
||
运算符执行逻辑OR
并给出布尔结果,仅此而已。Yes, JavaScript does it a bit differently. The expression
(something || 321)
means ifsomething
is of a falsy value, a default value of321
is used instead.In conditional expressions
||
acts as a logicalOR
as usual, but in reality it performs the same coalescing operation. You can test this with the following:In PHP the
||
operator performs a logicalOR
and gives a Boolean result, nothing else.我实际上很惊讶 javascript 也没有警报 1 或 true 。你想要的 js 语法是:
用括号括起来,将其评估为 true / falsey。对于 php 你是说:
php 中的匹配语句如下所示:
I'm actually surprised javascript did not alert 1 or true as well. The syntax you want for js is:
Wrapping parentheses around something evaluates it as truthy / falsey. For php your are saying:
A matching statement in php would look like:
只是添加 BoltClock 答案,因为我无法发表评论 - 如果您希望它是一个布尔值,您可以将其解析为 bool ,如下所示:
Just to add on boltClock answer since I can't comment - If you want it be a Boolean value you can parse it to bool like this:
在 PHP 中,
($var || 321);
被计算并分配给$other
。您可以在 PHP 中使用它。
更新:正如 BoltClock 在 Javascript 中所说,如果
something
为 false,var Somethingelse = (something || 321)
会寻求为变量分配一个默认值。In PHP
($var || 321);
is evaluated and assigned to$other
.You can use this in PHP.
Update: As BoltClock said in Javascript
var somethingelse = (something || 321)
seeks to assign a default value to the variable ifsomething
is false.