Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - Why doesn't my equality comparison using = (a single equals) work correctly?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

= is always assignment. Equality comparison is == (loose, coerces types to try to make a match) or === (no type coercion).

So you want

if (str === ''){
// -----^^^

not

// NOT THIS
if (str = ''){
// -----^

What happens when you do if (str = '') is that the assignment str = '' is done, and then the resulting value ('') is tested, effectively like this (if we ignore a couple of details):

str = '';
if (str) {

Since '' is a falsy value in JavaScript, that check will be false and it goes to the else if (str.length <= 9) step. Since at that point, str.length is 0, that's the path the code takes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...