实际工作中点滴总结

101 阅读2分钟

类型判断

用typeof 不能判断null和数组。

typeof([1,2,3])  //Object
typeof(null) //Object
typeof window.alert //function

用instanceof判断类型:原理是原型链来判断的;不能区分array,string和boolean

function Func(){}
const func = new Func();
func instanceof Func  //true

[1,2] instanceof Array //true
[1,2] instanceof Object //true
false instanceof Boolean //false
"12" instanceof String //false

每个对象都有一个toString()方法,当要将对象表示为文本值或以预期字符串的方式引用对象时,会自动调用该方法。默认情况下,从Object派生的每个对象都会继承toString()方法。如果此方法未在自定义对象中被覆盖,则toString()返回[Object type],其中type是对象类型。所以就有以下例子:

Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call("1"); // [object String]
Object.prototype.toString.call(1); // [object Numer]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]

封装type方法

var type = function(data) {
        var toString = Object.prototype.toString;
        var dataType = data instanceof Element
            ? 'element' // 为了统一DOM节点类型输出
            : toString
                .call(data)
                .replace(/\[object\s(.+)\]/, '$1')
            .toLowerCase()
        return dataType
    }

使用:结果都是小写的string 直接对比即可

type([1,2]) //arrary
type(null) //null
type(undefined) //undefined
type("undefinec") //string

深拷贝

深拷贝和浅拷贝的区别只是引用地址的区别

 function deepCopy(obj) {
        let newobj= null;
    //    判断数据类型是否是复杂类型,如果是就用递归,如果不是直接赋值
        if (typeof(obj)=="object" && obj!==null){
            //根据具体参数类型来赋值,是数组或者是队形
            newobj=obj instanceof Array?[]:{};
        //    循环obj
            for (var i in obj){
                newobj[i]=deepCopy(obj[i])
            }
        }
        else {
            newobj=obj
        }
        return newobj;
    }

null和undefined的区别

null表示空值,一般初始化时候赋值null,可以变为想变成的数据格式,undefined是声明未赋值。 1.变量声明了未赋值,是undefined

var test;
console.log(test) //undefined

2.调用函数时应该提供的参数没有提供,其为unfefined

(function( window, undefined) {

})(window)

3.对象没有赋值是undefined

var test={};
console.log(test.a) //undefined

4.函数没有返回值的时候

function test() {}
test(); //undefined

5.解构赋值的时候会使用undefined

const s={a:null};
const {a="a",b="b"}=s;
consolo.log(a,b) //null "b"

chenguangliang.com/blog/null与u…

各种状态码