js高级编程:js五种基本数据类型,number,string,boolean,undefined,null,外加一个复杂类型object(包括array,obj,function)
本篇主要解析下number
number value
number value即 number type的值,对number的表现
number type
number type 包括的number value有: NaN,+infinity,-infinity
number object
常见的强制转换 Number() 就是number object
NaN
not a number,但它是number type的。
NaN 的检测 isNaN
检测 NaN, isNaN会隐式地将非number type 值转换为number 再判断,所以使用该方法时最好组装一个,见下>
Number.isNaN = function (value) {
return typeof value === 'number' && isNaN(value);//es6下面已经这样实现
}
NaN 的检测 Object.is()投机取巧检测
Object.is(value1,value2)
当
both null,
both undefined,
both true or false,
both string && the same length with the same characters
both number and
both +0,
both -0,
both NaN,
both the same value which is not NaN or zero
both the same object
Object.is(NaN,NaN)
哪些情况下会得到NaN
-
浮点运算
parseInt(string),parseFloat(string),Math.floor(string)等等浮点运算会返回NaN
-
infinity的运算
Infinity - Infinity, Infinity + Infinity, 1 * Infinity Infinity是怎么得到的,常见的0作为除数时会产生Infinity
应用-数组去重(包含NaN的数组)
对数组[1,1,'1',NaN,NaN,null,null,undefined,undefined]去重
//function _isNaN (value) {
// return typeof value === 'number' && isNaN(value);
//}
function unique (arr) {
var type = '',
key = '',
res = [],
hash = {};
for(var i= 0,len=arr.length;i<len;i++){
//if(_isNaN(arr[i])){
// if(!hash[arr[i]]){
// hash['NaN'] = true;
// res.push(arr[i]);
// }
//}else{
type = typeof arr[i];
key = type + arr[I];
if(!hash[key]){
hash[key] = true;
res.push(arr[i]);
}
//}
}
return res;
}
总结一下
今天面了一个老东家滴滴实习生,涉及到此基础,发现应届生还是要重视基础,在此整理一下,仅供参考。
追加---数组去重问题进一步深入
通用数组去重方法,简洁而深入