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

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

  1. 浮点运算

      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字符串达到去重目的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值