[ 登录注册 ]

Web开发

一道Javascript的笔试题目

2016-05-13 10:24:48 admin 返回上一页

题目如下:

编写函数,用于过滤一个数组内重复的元素,并用这些元素重构一个新数组,新数组内也不能有重复元素。
Array.prototype.indexOf = function(val){
var index = -1;
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
index = i;
break;
}
}
return index;
}
Array.prototype.hasOf = function(val){
var has = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] === val)
has += 1;
}
return has;
}
Array.prototype.popRepeat = function(){
var arr = this, newArray = [], arrlen = arr.length, i = 0;
while (i < arrlen) {
if (arr.hasOf(arr[i]) > 1) {
arr.splice(i, 1);
arrlen–;
if (newArray.indexOf(arr[i]) < 0)
newArray.push(arr[i]);
}
else {
i++;
}
}
return newArray;
}
/**
* test
*/
var array = [6, 4, 4, 'abc',function(){alert('abc')},4, 4, {a:1,b:3,c:5}, 3, 3, 7, 1, {a:1,b:2}, 3, 3, 3, 2, 2, 2, 2, 9, 99, 9, 9, 5, 5];
var newArray=array.popRepeat();
alert(array);
alert(newArray);


文章来源:http://www.bozhiyue.com/mianshiti/Webkaifa/2016/0513/97071.html
返回上一页    返回分类 上一篇:   下一篇:
相关