每周前端知识整理(15.07.26)

来源:互联网 发布:数据机房建设方案 编辑:程序博客网 时间:2024/04/30 15:00

1.一道小题

同学也在准备前端面试。问了我一道题如下:

    var Cat = {        createNew : function() {            var cat = {};            cat.name = 'mimi';            var age = '10';            cat.getAge = function() {                this.age = '20';                alert(age);            };            return cat;        }    };    var cat1 = Cat.createNew();    cat1.getAge();

代码最终alert为10。那么为什么不是20呢?

这里面主要涉及到了this的含义和闭包。在执行了

var cat1 = Cat.createNew();

后,cat1类型为object,拥有一个属性即name='mimi',而一个方法getAge。这个时候age='10'其实和他关系不大的,因为cat1完全时候return的cat对象决定的。

之后

    cat1.getAge();
进入到这个function后,this指向的事cat1,所以在this.age='20'后,cat1就有了第二个属性即age:20。

但当执行

alert(age);

时,在getAge这个function内部是找不到age属性的,所以只能到上一级作用域寻找,于是找到了10。所以最终alert10。而这里实际上也形成了闭包。

2.如何删除数组中重复项?

这应该是个很常见的问题了。不光是在JS领域。在其他语言环境中也很常见,但是JS的array又有着显著的不同,他可以放不同类型的数据,像这样:

var a = [1,'b',{c:4}]

目前来看,如果是纯数字的数组的话,下面这种方式比较好

var arr = [1, 2, 2, 3, 4, 5, 6, 6];function getArray(a) { var hash = {},     len = a.length,     result = []; for (var i = 0; i < len; i++){     if (!hash[a[i]]){         hash[a[i]] = true;         result.push(a[i]);     }  } return result;}
这种方式利用了类似哈希表的方式,感觉是JS独有的一种方式。并且对数组是否有序没有要求。但是,如果当前数组内包含string活object那么上方法就无效了。

还有一些开源库提供了类似的排序方法。比如underscore,jquery,google closure library下面这篇文章对比了这三种的性能

http://segmentfault.com/q/1010000000197274

由此可见underscore并不是很优质的,google的方法应该是最稳定最全面的。原文没有贴出google源码和分析。

下面贴出google源码

/** * Removes all duplicates from an array (retaining only the first * occurrence of each array element).  This function modifies the * array in place and doesn't change the order of the non-duplicate items. * * For objects, duplicates are identified as having the same unique ID as * defined by {@link goog.getUid}. * * Alternatively you can specify a custom hash function that returns a unique * value for each item in the array it should consider unique. * * Runtime: N, * Worstcase space: 2N (no dupes) * * @param {Array<T>|goog.array.ArrayLike} arr The array from which to remove *     duplicates. * @param {Array=} opt_rv An optional array in which to return the results, *     instead of performing the removal inplace.  If specified, the original *     array will remain unchanged. * @param {function(T):string=} opt_hashFn An optional function to use to *     apply to every item in the array. This function should return a unique *     value for each item in the array it should consider unique. * @template T */goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {  var returnArray = opt_rv || arr;  var defaultHashFn = function(item) {    // Prefix each type with a single character representing the type to    // prevent conflicting keys (e.g. true and 'true').    return goog.isObject(item) ? 'o' + goog.getUid(item) :        (typeof item).charAt(0) + item;  };  var hashFn = opt_hashFn || defaultHashFn;  var seen = {}, cursorInsert = 0, cursorRead = 0;  while (cursorRead < arr.length) {    var current = arr[cursorRead++];    var key = hashFn(current);    if (!Object.prototype.hasOwnProperty.call(seen, key)) {      seen[key] = true;      returnArray[cursorInsert++] = current;    }  }  returnArray.length = cursorInsert;};
代码先记录到此,具体分析之后补上


0 0
原创粉丝点击