string - Javascript answer changes depending on comparison order -



string - Javascript answer changes depending on comparison order -

i'm relatively new javascript (learned ruby first) have been confused unusual inconsistencies i've been seeing , i'm trying figure out underlying mechanisms can improve understand language. 1 of these when i'm doing comparing shouldn't matter on side of === sign 2 elements are, i've seen happen , don't understand why. here's illustration basic function see if string sorted alphabetically or not:

this version returns true:

function sorted(str) { var arr = str.split(""); homecoming arr.sort().join('') === arr.join(''); } sorted('abc') // => true sorted('cba') // => true

while homecoming right answer:

function sorted(str) { var arr = str.split(""); homecoming arr.join('') === arr.sort().join(''); } sorted('abc') // => true sorted('cba') // => false

i've tried figure out , pretty stuck - can help explain?

thank you!

unlike of methods of array.prototype, sort() manipulates object in place. hence, in first snippet arr in sec operand of === sorted already, , comparing returns true.

javascript string sorting join comparison

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -