我无法理解这段代码

时间:2018-04-04 08:29:37

标签: javascript arrays typeof

我必须删除数组中的相同数据。
我发现这个代码和它的工作完全按照我想要的方式但是我无法理解这部分代码 请解释这段代码,这是什么>>> a [this [i]] <<<<

Array.prototype.unique = function() {
    var a = {}; //new Object
    for (var i = 0; i < this.length; i++) {
        if (typeof a[this[i]] == 'undefined') {
            a[this[i]] = 1;
        }
    }
    this.length = 0; //clear the array
    for (var i in a) {
        this[this.length] = i;
    }
    return this;
  };

2 个答案:

答案 0 :(得分:1)

请在每行解释该行代码之前查看注释 //为数组原型添加了唯一函数,以便所有数组都可以具有唯一的//函数访问

    Array.prototype.unique = function() {
        //creating a temp object which will hold array values as keys and 
         //value as "1"  to mark that key exists
        var a = {}; //new Object
        //this points to the array on which you have called unique function so
        //if arr = [1,2,3,4] and you call arr.unique() "this" will point to 
        //arr in below code iterating over each item in array
        for (var i = 0; i < this.length; i++) {
        //idea is to take the value from array and add that as key in a so 
        //that next time it is defined. this[i] points to the array item at 
        //that index(value of i) //and a[this[i]] is adding a property on a 
        //with name "this[i]" which is the value //at that index  so if value 
        //at that index is lets say 2 then a[this[i]] is //referring to 
        //a["2"].thus if 2 exists again at next index you do not add it to a
        //again as it is defined
            if (typeof a[this[i]] == 'undefined') {
                a[this[i]] = 1;
            }
        }
        this.length = 0; //clear the array
        //now in a the properties are unique array items you are just looping 
        //over those props and adding it into current array(this) in which 
        //length will increase every //time you put a value 
        for (var i in a) {
            this[this.length] = i;
        }
        //at the end returning this which is the modified array
        return this;
      };

//修改

[this [i]]的存储值是1,对于它中的所有键都是1。 你从

开始
arr = [1,2,3,2,3,4];

当你打电话给arr.unique时 第一个循环中的代码创建了类似这样的东西

a = {
"1":1,
"2":1,
"3":1,
"4":1
}

因此您可以看到只有唯一值作为a中的属性。 现在在for-in循环中,你只需要取一个(即1,2,3,4)的键并将其添加到数组(这个)。

希望如果您需要更多详细信息,请告知我们

答案 1 :(得分:0)

a[this[i]] =&gt;
this[i] - &gt;从当前对象获取i元素,在这种情况下它是数组 a[] - &gt;在var a中指定的位置获取[]的元素,在这种情况下,this[i]内的值是什么