1

你好在php中我可以这样做:

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

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

4

7 回答 7

4

它仍然适用于javascript

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

输出

it is zero!
于 2013-11-07T10:56:12.707 回答
1

这应该有效:

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

顺便说一下,它被称为三元运算符。许多语言都支持它们

于 2013-11-07T10:56:25.353 回答
1

几乎完全一样。

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

输出:

"it is zero!"
于 2013-11-07T10:56:38.610 回答
1

除了你的 $ 变成 var 之外,没有什么大的区别。

文件

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

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

演示:http: //jsfiddle.net/jayeshjain24/efLYf/

于 2013-11-07T10:57:21.990 回答
1

Javascript 还支持三元运算符。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

于 2013-11-07T10:57:43.850 回答
1
(value == 0)?alert('it is zero!'):alert('It is not zero.');
于 2013-11-07T10:58:20.753 回答
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));

it is zero当值未定义或错误时,要避免来自登录的代码:

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

这只会it is zerovalueis'0'或时记录0。它不适用于像false, undefined, null...

于 2013-11-07T11:00:49.687 回答