I came across this bug while trying to run a JS conditional to check for an empty string. In Chrome debugger, the empty string evaluates with a length of 1 and sometimes even 2. It's happening in a react app. I'm pretty lost as to how the proto still works correctly but the normal length method doesn't.
I came across this bug while trying to run a JS conditional to check for an empty string. In Chrome debugger, the empty string evaluates with a length of 1 and sometimes even 2. It's happening in a react app. I'm pretty lost as to how the proto still works correctly but the normal length method doesn't.
Share Improve this question edited Dec 11, 2018 at 22:55 Geek Num 88 5,3122 gold badges23 silver badges36 bronze badges asked Nov 30, 2018 at 17:57 Jeremy GottfriedJeremy Gottfried 1,20116 silver badges32 bronze badges 5- 1 Is it whitespace? Or possibly a line break? – Ryan Wilson Commented Nov 30, 2018 at 17:59
- 1 Are you sure that there is no character? Maybe you just can't see it ... – Jonas Wilms Commented Nov 30, 2018 at 18:00
-
3
An empty string, by definition, has 0 characters. Thus the string shown is not empty: even if there are no visible characters. Use
value.charCodeAt(0)
to see what character is really there (value[0]
won't be useful because it returns a string itself). – user2864740 Commented Nov 30, 2018 at 18:00 -
Just tried on Chrome console.
value = '' value.length // 0
– pmkro Commented Nov 30, 2018 at 18:01 - 2 Ah yes, charCodeAt worked, thanks! It's apparently an enter – Jeremy Gottfried Commented Nov 30, 2018 at 18:04
2 Answers
Reset to default 3A string may appear visibly empty when you ask for its value if the string contains characters that are not normal characters. These strings could be generated via the String.fromCharCode
method or implicitly like '\x0d'
. Characters such as Enter will appear to be an empty string. You can check for invisible characters using the charCodeAt
method.
As Matus showed, this will replicate the behavior in question:
v = '\x0d'
console.log(v); // ""
console.log(typeof v); // "string"
console.log(v[0]); // ""
console.log(v.length); // "1"
It is probably on of these cases (invisible characters)
v = '\x0d'
console.log(v); // ""
console.log(typeof v); // "string"
console.log(v[0]); // ""
console.log(v.length); // "1"
v = '\x0d\x0d'
console.log(v); // ""
console.log(typeof v); // "string"
console.log(v[0]); // ""
console.log(v.length); // "2";
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745515047a4630945.html
评论列表(0条)