javascript - jquery string comparison variable -
i have following code:
arr = ["abc", "def", "ghi", "jkl"] arr2 = ["abc", "def", "ghi", "jkl"] $(arr).each(function(){ thiselem = this; $(arr2).each(function(){ if(thiselem == "abc" && == "abc") alert("case 1"); if(thiselem == this) alert('case 2'); }); }); when run "case 1" pops up. logically statement should true transitive property, guessing javascript string syntactic issue or jquery scope thing messing up. advice appreciated.
other posters have suggested workarounds, i'll try answer question why original code doesn't work. answer rather non-trivial , reveals good-to-know javascript gotchas.
jquery.each uses apply pass this callback. when apply's argument primitive value, string, "boxed", i.e. converted object (specifically, string object):
console.log(typeof("cat")) // string logger = function() { console.log(typeof(this)) } logger.apply("cat") // object now consider following:
a = ["abc"] b = ["abc"] $(a).each(function() { var = $(b).each(function() { console.log(this == that) // false! }) }) although a[0] , b[0] "obviously" equal, == operator returns false because both objects, , 2 object variables equal if physically same object. on other side, works expected:
a = ["abc"] b = ["abc"] $(a).each(function() { console.log(this == "abc") // true console.log(this == b[0]) // true }) when js compares object string, object converted string primitive using tostring. since this string object, tostring returns primitive string made of, , 2 primitive strings equal if characters equal.
Comments
Post a Comment