admin管理员组文章数量:1328749
While debugging a javascript code that uses jQuery I found the following code:
[0, 0].sort(function()
{
baseHasDuplicate = false;
return 0;
});
By my understanding of javascript this code will sort array containing two zeroes with parison function that will always set a global variable and will return equality, which has same effect as baseHasDuplicate = false;
.
Coming from a valued source I think I missed something.
Did I miss something or is this a programming fail?
While debugging a javascript code that uses jQuery I found the following code:
[0, 0].sort(function()
{
baseHasDuplicate = false;
return 0;
});
By my understanding of javascript this code will sort array containing two zeroes with parison function that will always set a global variable and will return equality, which has same effect as baseHasDuplicate = false;
.
Coming from a valued source I think I missed something.
Did I miss something or is this a programming fail?
1 Answer
Reset to default 12As you can see here (chinese), this code might be used to test for Chrome. EDIT: see below for the plete story..
As explained in the article, what happens is that Chrome optimizes the ".sort(...)" method in such a way that the [0, 0].sort(...)
call won't execute the given parison function.
From the article, Chrome's implementation of ".sort(...)" is something like:
function sort(parefn) {
var custom_pare = (typeof(parefn) === 'function');
function Compare(x,y) {
if (x === y) return 0;
if (custom_pare) {
return parefn.call(null, x, y);
}
...
}
As 0 === 0
is true, it won't call parefn
.
In the case of jQuery, it won't set the global variable baseHasDuplicate
to false
.
EDIT: if you browse Sizzle's source code, here for example (go to the yellow section under "Sizzle CSS Selector Engine", called "Sizzle variables"), you will find the following explanation:
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our parision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function(){
baseHasDuplicate = false;
return 0;
});
Looks demystified!
本文标签: jqueryWhat does this (useless) javascript code doStack Overflow
版权声明:本文标题:jquery - What does this (useless?) javascript code do? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742260076a2442350.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论