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

在重新写一个服务的接口

原来程序是php写的

看php文档 empty() 这个是用来检测非空值的

那么在js里

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

是否等于js的

if(x){
todo...
}
阅读 2.1k
1 个回答
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, 统一用IEEE-754表示, 所以会有NaN, -0, Infinity等几个特殊值.

如果可以对比的话:

  1. 相同的是空字符串"", NULL/null, FALSE/false, 0(0.0)/0都会假
  2. 不同的是空数组[]在PHP中为假, JS中为真
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题