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

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

在重新寫(xiě)一個(gè)服務(wù)的接口

原來(lái)程序是php寫(xiě)的

看php文檔 empty() 這個(gè)是用來(lái)檢測(cè)非空值的

那么在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)

不同語(yǔ)言沒(méi)法比, 比如:

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

如果可以對(duì)比的話:

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