最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

type coercion - Why do some non-empty strings evaluate to "false" in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

According to this table in the ECMAScript standard, string values that have length 0 should be evaluated as boolean false.

How e, then, these statements evaluate to true?

"\t" == false
" " == false
"\n" == false
"     " == false

All those strings have a length greater than 0. For example:

While I understand that "0" evaluates to false because it can be coerced to a numeric 0, I can't explain why these strings are falsey. What's going on?

(Obviously I can use === for a strict parison, but in this case in my code, I need the loose parison, however I wasn't expecting a non-empty string to be considered falsey.)

According to this table in the ECMAScript standard, string values that have length 0 should be evaluated as boolean false.

How e, then, these statements evaluate to true?

"\t" == false
" " == false
"\n" == false
"     " == false

All those strings have a length greater than 0. For example:

While I understand that "0" evaluates to false because it can be coerced to a numeric 0, I can't explain why these strings are falsey. What's going on?

(Obviously I can use === for a strict parison, but in this case in my code, I need the loose parison, however I wasn't expecting a non-empty string to be considered falsey.)

Share Improve this question edited Nov 19, 2014 at 20:10 Matt asked Nov 19, 2014 at 20:04 MattMatt 23.8k18 gold badges74 silver badges116 bronze badges 3
  • In which browser/environment are you seeing this behavior? – Reinstate Monica -- notmaynard Commented Nov 19, 2014 at 20:08
  • probably duplicated with this page of stackoverflow:stackoverflow./questions/5634372/… – Reza Commented Nov 19, 2014 at 20:09
  • @vagueness Yeah, pretty much. It didn't show up in my searches, unfortunately. – Matt Commented Nov 19, 2014 at 20:11
Add a ment  | 

1 Answer 1

Reset to default 10

You are using loose parison, which performs type conversion. Whenever you pare against a Boolean, both values are actually converted to numbers (spec, steps 7 and 5). false is 0 and (surprisingly!)every string containing only white space characters is converted to 0 as well (when converted to a number) (spec):

The MV of StringNumericLiteral ::: StrWhiteSpace is 0.


I wasn't expecting a non-empty string to be considered falsey

Comparing a value against a Boolean is very different from converting a value to a Boolean. "Falsy" means that the value is converted to false when converted to a Boolean. However, again, in your case the values are converted to numbers first.

Example:

Number("    ") // 0 ( == Number(false))
// vs
Boolean("    ") // true
发布评论

评论列表(0)

  1. 暂无评论