Javascript数组权重删除方法(四种)详细解决方案及实例代码
Javascript数组权重删除的四种方法四种算法用于实现这一目标:
第一种方法:
(array.prototype.unique1 =功能){
新的临时数组
对于(var i = 0;i < this.length; / /我+ +)当前数组的遍历
{
如果当前数组已保存到临时数组中,则跳过,
否则将推送到临时数组中。
如果(n.indexof(这{我})= 1(这n.push {我}));
}
返回N;
}
第二方法:
array.prototype.unique2 =功能()
{
用于临时数组的var、{ = }、r = {、}、n、n、r
对于(var i = 0;i < this.length; / /我+ +)当前数组的遍历
{
如果({这个{ } }!)如果哈希表中没有当前项
{
在哈希表中,这个{ } = true;
R.push(本{我}); / /投入临时阵列电流推力电流阵列
}
}
返回R;
}
var arr = { 1,A,A,B,D,E,e,1, 0 }
警报(arr.unique2());
第三方法:
array.prototype.unique3 =功能()
{
{此{ 0 } };数组结果
对于(var i = 1;i < this.length; / /我+ +)从第二导线
{
如果我第一次出现在数组中当前位置的当前数组不是i,
因此,重复i,忽略,否则,保存结果数组。
If (this.indexOf (this{i}) = I n.push (this{i}));
}
返回N;
}
这些第一和第三是用数组中的索引的方法。这种方法的目的是在阵列的输入参数的第一次出现的位置。很显然,JS引擎遍历数组直到目标被发现时,它的实现。所以这个功能会浪费很多时间和方法2用在哈希表中。放在下标的形式已经存在为对象的下标引用数组的索引比搜索要快得多。
为了确定这三种方法的效率,我做了一个测试程序生成10000个随机数的数组的长度,然后用几种方法测试的执行时间。结果表明,二方法比其他两种方法快得多。但应该超过内存占用二方法,因为有一个哈希表,这是所谓的空间时间。这是测试页面,你可以去看看。
第四方法:
array.prototype.unique4 =功能()
{
This.sort();
var {此{ 0 } };
对于(var i = 1;i < this.length;i++)
{
如果({ { })!=重新{重新length-1 })。
{
Re.push(本{我});
}
}
重新回归;
}
The idea of this approach is to sort the array first and compare the two adjacent values.The JS native sort method used when sorting, the JS engine should be used in the quick sort.The result of the final test is that the average running time of this method is about three times that of the second methods, but it is much faster than the first and the third.
谢谢你的阅读。我希望你能帮助你,谢谢你对这个站的支持。