这个赋值结构叫什么?你可以在Php中做吗? [英] What is this assignment construct called? And can you do it in Php?
问题描述
var foo = other_var || 默认值;
在Javascript中,如果左侧是伪造的,则右侧的值被分配。 / p>
它非常方便,并且可以节省更长时间和不必要的显式三进制表达式。
是否有这个名称一种构造?
奖金:在Php中没有使用三元运算符的方法吗?
PS:另一个变体是如果你没有得到一个真实的值而不是给出一个默认值,那就是抛出一个错误:
var foo = something || alert(foo not set!);
逻辑或(通常 在某些(如 C,C ++ )中,它的运算符在许多语言中是非常不同的如下所示:评估左边;如果是真的,返回true,否则评估右侧,否则返回true,否则返回true。结果总是在这里布尔值。 在其他(如 Javascript,Python )中,我相信PHP也更像:评估左侧;如果它是真的,返回它,否则评估右边并返回结果。然后,结果可以是任何类型,你可以像这样的结构: 或非常喜欢: I have often used the following construct in Javascript: In Javascript, if the left side is falsy, then the value on the right side is assigned. It is very handy, and saves writing longer and unnecessarily explicit ternary expressions. Is there a name for this sort of construct ? Bonus: Is there a trick to do this in Php without using a ternary operator? PS: another variant is to throw an error if you don't get a truthy value, instead of giving a default value:
The logical-or (usually In some (like C, C++) it works like: "Evaluate the left-hand side; if it's true, return true, otherwise evaluate the right hand-side and return true if it's true or false otherwise." The result is always boolean here. In others (like Javascript, Python, I believe that PHP also) it's more like: "Evaluate the left-hand side; if it's true, return it, otherwise evaluate the right-hand side and return the result." Then the result can be of any type and you can do constructs like: or quite fancy:
这篇关于这个赋值结构叫什么?你可以在Php中做吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
a =(b || c); //等同于a = b? b:c;
function compare(A,B){//如果A B
返回Bx - Ax || B.y - A.y;
}
var foo = other_var || "default_value";
var foo = something || alert("foo is not set!");
||
) operator is drastically different in many languages.a = (b || c); // equivalent to a = b ? b : c;
function compare(A, B) { // -1 if A<B, 0 if A==B, 1 if A>B
return B.x - A.x || B.y - A.y;
}