javascript内联if变量赋值如php

时间:2013-11-07 10:54:32

标签: javascript php ternary-operator

你好,我可以这样做:

$value = 0;
$test = $value === 0 ? 'it is zero!' : 'It is not zero.';
echo $test;

如何在不使用经典if - else if语句的情况下在php中的1行中完成此操作?

7 个答案:

答案 0 :(得分:4)

它仍然适用于javascript

value = 0;
var test = (value === 0 ? 'it is zero!' : 'It is not zero.');
console.log(test);

<强>输出

it is zero!

答案 1 :(得分:1)

这应该有效:

var value = 0;
var test = (value === 0) ? 'It is zero' : 'It is not zero!';
console.log(test);

顺便说一下,它被称为三元运算符。 Many languages support them

答案 2 :(得分:1)

几乎完全一样。

var value = 0;
var test = (value === 0) ? 'it is zero!' : 'it is not zero';
console.log(test);

输出:

"it is zero!"

答案 3 :(得分:1)

除了你的$变成var。

之外没有这么大的区别

documentation

我总是喜欢内联三元。我个人觉得它更具可读性。

var test =(value===0)?'it is zero!':'It is not zero.';
console.log("test check==="+test)

DEMO:http://jsfiddle.net/jayeshjain24/efLYf/

答案 4 :(得分:1)

答案 5 :(得分:1)

(value == 0)?alert('it is zero!'):alert('It is not zero.');

答案 6 :(得分:0)

我可以在JS中做得更好1:

var value = 0;
console.log(value === 0 ? 'It is zero!' : 'it is not zero');

甚至更短:

console.log('it is ' + ((value = 0) === 0 ? '':'not ') + 'zero!');

Bang,你的3个PHP行的一行。请注意,如果value不存在,则 将导致抛出错误(在严格模式下)或正在创建隐含的全局变量。
但是,如果变量value已经存在,那么所有变量都可以正常运行,并且行为与您期望的一样:

var value = 0;
console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
//logs it is zero
value = 123;
console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
//logs it is not zero

我使用IIFE进行了测试:

(function(value)
{//logs it is zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}());
    (function(value)
{//logs it is not zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}(123));
(function(value)
{//logs it is zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}(0));

当值未定义或伪造时,要避免来自loggin it is zero的代码:

(function(value)
{//coerce to numbner
    console.log('it is ' + (value === 0 || value === '0' ? '':'not ') + 'zero!');
}());

如果it is zerovalue'0',则只会记录0。它不适用于falseundefinednull ...

等值