当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 浅谈Object.prototype.toString.call()方法

浅谈Object.prototype.toString.call()方法

2019年08月01日  | 移动技术网IT编程  | 我要评论

javascript里使用typeof判断数据类型,只能区分基本类型,即:numberstringundefinedbooleanobject
对于nullarrayfunctionobject来说,使用typeof都会统一返回object字符串。
要想区分对象、数组、函数、单纯使用typeof是不行的。在js中,可以通过object.prototype.tostring方法,判断某个对象之属于哪种内置类型。
分为nullstringbooleannumberundefinedarrayfunctionobjectdatemath
1. 判断基本类型

object.prototype.tostring.call(null); // "[object null]"
object.prototype.tostring.call(undefined); // "[object undefined]"
object.prototype.tostring.call(“abc”);// "[object string]"
object.prototype.tostring.call(123);// "[object number]"
object.prototype.tostring.call(true);// "[object boolean]"

2. 判断原生引用类型

**函数类型**
function fn(){
  console.log(“test”);
}
object.prototype.tostring.call(fn); // "[object function]"
**日期类型**
var date = new date();
object.prototype.tostring.call(date); // "[object date]"
**数组类型**
var arr = [1,2,3];
object.prototype.tostring.call(arr); // "[object array]"
**正则表达式**
var reg = /[hbc]at/gi;
object.prototype.tostring.call(reg); // "[object regexp]"
**自定义类型**
function person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new person("rose", 18);
object.prototype.tostring.call(arr); // "[object object]"

很明显这种方法不能准确判断personperson类的实例,而只能用instanceof 操作符来进行判断,如下所示:

console.log(person instanceof person); // true

3. 判断原生json对象

var isnativejson = window.json && object.prototype.tostring.call(json);
console.log(isnativejson);// 输出结果为”[object json]”说明json是原生的,否则不是;

注意:object.prototype.tostring()本身是允许被修改的,而我们目前所讨论的关于object.prototype.tostring()这个方法的应用都是假设tostring()方法未被修改为前提的。
4. 实例:为array对象添加一个去除重复项的方法

input
[false, true, undefined, null, nan, 0, 1, {}, {}, 'a', 'a', nan].uniq()
output
[false, true, undefined, null, nan, 0, 1, {}, {}, 'a']

这里要注意,nan === nan 为false,{} === {}为false。

array.prototype.uniq = function () {
    if (!this.length || this.length == 0) return this;
    var res = [], key, hasnan = false, temp = {};
    for (var i = 0 ; i < this.length; i++) {
        if (typeof this[i] === 'object') {
            res.push(this[i]);
        } else if (this[i] != this[i]) { // 如果当前遍历元素是nan
            if (!hasnan) {
                res.push(this[i]);
                hasnan = true;
            }
        } else {
            key = typeof(this[i]) + this[i];
            if (!temp[key]) {
                res.push(this[i]);
                temp[key] = true;
            }
        }
    }
    return res;
}

另一种解法:

array.prototype.uniq = function () {
    var res = [];
    var flag = true;
    this.foreach(function(x) {
        if (res.indexof(x) == -1) {
            if (x != x) {
                if (flag) {
                    res.push(x);
                    flag = false;
                }
            } else {
                res.push(x);
            }
        }
    })
    return res;
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网