To add a new API to the prototype of the built-in object, that is, write a new public method through the prototype, and then call the method through the object of the array.
The new API implementation method is added to the built-in object: Constructor.prototype.newFunctionName = function () {…}
/**
* 数组去重 API
* 定义一个 hash数组用其下标存储 arr的元素值,以去除重复的元素
* 定义一个新的 result数组存储 arr去重后的元素,调用结束后作为返回值
*/
Array.prototype.removalDup = function(){
var hash = [],
result = [];
if(this.length){
for(var i = 0; i < this.length;i++){
// 判断 hash数组中的元素是否为 undefined再取反
if(!hash[this[i]]){
// 未重复的元素赋上任意的值(只要 Boolean值为 true即可)
hash[this[i]] = true;
// 将未重复的元素插入到 result数组中
result.push(this[i]);
}
}
}
// 返回去重后的 result数组
return result;
}
var arr = [3,2,3,3,2,4,5,2,2,6,3,8,9,3,10];
var new_arr = arr.removalDup();
Output effect:
Array.prototype method without adding deduplication API:
Initial elements of array arr: [3,2,3,3,2,4,5,2,2,6,3,8,9,3,10]
###### The method of adding Array.prototype to the deduplication API:
Compared with the original Array prototype, it is obvious that the new Array adds an API we wrote: removalDup ();