前端面試-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字符串達到去重目的

相關文章
相關標籤/搜索