if (obj !== obj) does somethig?
In this page you can see the following example of how to implement an indexOf for arrays:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n) // <-- code of interest
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(M开发者_如何转开发ath.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
My question is about the line:
if (n !== n)
in which case would this boolean expression return true
?
it's a shortcut for verifying if the number is NaN.
say if you have n = Number("string");
then n !== n
would evaluate to true
.
in this case you could've use if(isNaN(n))
instead of if(n !== n)
.
That is how you check for NaN
. They are probably doing this as a precaution because it is possible to over write the global function isNaN
.
// most of the time you don't need to try to simulate the specification so exactly-
if(!Array.prototype.indexOf){
Array.prototype.indexOf= function(what, i){
if(i==undefined || isNaN(i)) i= 0;
var L= this.length;
while(i< L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
}
精彩评论