前端面试-js之number数据类型特殊-NaN

js高级编程:js五种基本数据类型,number,string,boolean,undefined,null,外加一个复杂类型object(包括array,obj,function)javascript

本篇主要解析下numberjava

number value

number value即 number type的值,对number的表现es6

number type

number type 包括的number value有: NaN,+infinity,-infinity编程

number object

常见的强制转换 Number() 就是number objectsegmentfault

NaN

not a number,但它是number type的。数组

NaN 的检测 isNaN

检测 NaN, isNaN会隐式地将非number type 值转换为number 再判断,因此使用该方法时最好组装一个,见下>code

Number.isNaN = function (value) {
    return typeof value === 'number' && isNaN(value);//es6下面已经这样实现
}

NaN 的检测 Object.is()投机取巧检测

Object.is(value1,value2)
ip

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

  1. 浮点运算get

    parseInt(string),parseFloat(string),Math.floor(string)等等浮点运算会返回NaN
  2. 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;
}

总结一下

今天面了一个老东家滴滴实习生,涉及到此基础,发现应届生仍是要重视基础,在此整理一下,仅供参考。

追加---数组去重问题进一步深刻

通用数组去重方法,简洁而深刻

利用JSON字符串达到去重目的

相关文章
相关标签/搜索