javascript数组唯一化实现方式
实现方式
这里给出2中实现方式。一种是大家应该都知道的indexOf检测的方式,另一种是结合lastIndexOf和splice实现方式。
//首先给Array对象原型上添加indexOf和lastIndexOf方法.(如果没有的话)
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function(element, index){
var length = this.length;
if(index == null){
index = 0;
}else{
index = +index || 0;
if(index < 0) index+= length;
if(index < 0) index = 0;
}
for(var current;index<length;index++){
current = this[index];
if(current === element) return index;
}
return -1;
}
}
if(!Array.prototype.lastIndexOf){
Array.prototype.lastIndexOf = function(element, index){
var length = this.length;
if(index == null){
index = length - 1;
}else{
index = +index || 0;
if(index < 0) index+= length;
if(index < 0) index = -1;
else if(index >= length) index = length - 1;
}
for(var current;index>=0;index--){
current = this[index];
if(current === element) return index;
}
return -1;
}
}
//很常见的实现方式
var arrayUnique1 = function(arr){
for(var i=0,len=arr.length,result=[],item;i<len;i++){
item = arr[i];
if(result.indexOf(item) < 0) {
result[result.length] = item;
}
}
return result;
}
//通过lastIndexOf和splice方法实现方式
var arrayUnique2 = function(arr){
var length = arr.length;
while(--length){
//如果在前面已经出现,则将该位置的元素删除
if(arr.lastIndexOf(arr[length],length-1) > -1) {
arr.splice(length,1);
}
}
return arr;
}
测试结果
测试数据:var arr = [1,2,3,1,2,3,2,1,3,4,2,232];
IE7循环10,000次:
arrayUnique1为460ms,arrayUnique2为190ms。
FF3.5循环100,000次:
相关文档:
scrollHeight: 获取对象的滚动高度。
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
scrollWidth:获取对象的滚动宽度
offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度
offsetL ......
注意:readOnly中的O要大写
//页面初始化录入,判断指标说明是否为工资性支出。
function init() {
var mark = "<%=mark%>";
//如果指标说明为“工资性支出”,则工资支出那一项变为只读,且值为“指标可用金额”;其他录入框都不可录入。
......
Although the days of long and tedious code branches to target specific browsers in JavaScript are over, once in a while it's still necessary to do some simple code branching and object detection to ensure that a certain piece of code is working properly on a user's machine.
In this article, I ......
1.javascriptでURLの"?"以降のパラメータを取得:
var query = window.location.search.substring(1);
var pairs = query.split("&");
2.IE浏览器默认的功能停止
(Tab键在地址栏等中的移动停止)
function stopDefaultKey(){
window.e ......
<!--
/* Font Definitions */
@font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;
mso-font-alt:SimSun;
mso-font-charset:134;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 135135232 16 0 262145 0;}
@font-face
{font-family:"Cambria Mat ......