1. 程式人生 > 其它 >Object.prototype.toString.call()方法!!!給我記住!!

Object.prototype.toString.call()方法!!!給我記住!!

技術標籤:jsjs

淺談Object.prototype.toString.call()方法

該文章疑惑點解析:

引用:

  1. 例項:為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;
}

另一種解法解析

  1. 這裡是針對於NaN,push第一個出現的NaN
if (x != x) {
                if (flag) {
                    res.push(x);
                    flag = false;
                }
            }
  1. 這裡是針對{}和其他,push{}和其他
    else { res.push(x); }
  • 關於{}!={}
    -在這裡插入圖片描述

  • {}!={} 單純這樣子平常除錯是true;
    但是在裡forEach面的話判斷的是同一個{},所以forEach裡面{}=={},{}!={}是false

所以{}執行的是 else {
res.push(x);
}

而NaN執行的是
if (x != x) {
if (flag) {
res.push(x);
flag = false;
}
}