鍍金池/ 問答/PHP  HTML/ php中的 if (!empty($x))是否等同于 js 的 if(x) ?

php中的 if (!empty($x))是否等同于 js 的 if(x) ?

在重新寫一個服務的接口

原來程序是php寫的

看php文檔 empty() 這個是用來檢測非空值的

那么在js里

if (!empty($x)){
todo...
}

是否等于js的

if(x){
todo...
}
回答
編輯回答
萌小萌
Return Values ?

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

不同語言沒法比, 比如:

  1. 如果變量foo($foo)不存在, PHP的empty($foo)不會報錯, 返回FALSE, 而JS中!foo則會報ReferenceError`
  2. JS中有undefined類型而PHP中沒有
  3. JS中有NaNPHP中沒有
  4. JS中沒有floatint的概念, 都是number, 統(tǒng)一用IEEE-754表示, 所以會有NaN, -0, Infinity等幾個特殊值.

如果可以對比的話:

  1. 相同的是空字符串"", NULL/null, FALSE/false, 0(0.0)/0都會假
  2. 不同的是空數(shù)組[]在PHP中為假, JS中為真
2017年11月18日 03:51