分类 JavaScript 下的文章

let sugurl = "https://suggestion.baidu.com/su?wd=#content#&cb=window.baidu.sug",
                    script = document.createElement("script");
                sugurl = sugurl.replace("#content#", config.serarchValue);
                script.src = sugurl;
                document.getElementsByTagName("head")[0].appendChild(script);
                window.baidu = {
                    sug: function (json) {
                        if (json.s.length > 0) {
                            let d = [];
                            for (let i in json.s) {
                                d.push({keywords: json.s[i]});
                                if (i == (config.searchlimit - 1)) break;
                            }
                            config.searchData.list = d;
                            template();
                        }
                    }
                };

由于typeof只能判断5中基本类型:即 “number”,”string”,”undefined”,”boolean”,”object”

对于数组、函数、对象来说并不能详细的检测出类型, 这里使用的是对象的一个原生扩展函数,用来更精确的区分数据类型。
详细的判断类型给出如下:

console.log(Object.prototype.toString.call("jerry"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
console.log(Object.prototype.toString.call(new Person));//[object Object]

由此可进一步封装成自己需要的方法,需要时调用。

getType: function(j){
    let type = Object.prototype.toString.call(j) , ret;
    switch(type){
        case '[object Function]':
            ret = 'function';
        break;
        case '[object String]':
            ret = 'string';
        break;
        case '[object Number]':
            ret = 'number';
        break;
            case '[object Object]':
        ret = 'object';
            break;
        case '[object Array]':
            ret = 'array';
        break;
        default:
            ret = false;
    }
    return ret;
},

测试类型

let data = ['xx','aa'];
console.log(this.getType(data))
// array