1.数组去重
有两个方法,一个用对象,一个用数组的indexOf方法
Array.prototype.unique = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
=====================================================
function unique(arr){
var newArr = [];
for(var i = 0; i < arr.length; i++) {
if(newArr.indexOf(arr[i]) == -1) {
newArr.push(arr[i]);
}
}
return(newArr);
}
2.清除开头结尾的空格
function trim(str){
return str.replace(/^\s+/,"").replace(/\s+$/,"");
}
3.冒泡排序
function bubbleSort(arr){
var temp;
for(var i=0;<arr.length ; i ++){
for(var j = 0;j < arr.length - 1;j ++){
if(arr[i] < arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
4.字符串中出现次数最多的字母
function findItem(str){
var maxLength = 0;
var result =‘’;
while(str !=‘’){
var oldStr = str;
var getStr = str.substr(/”+ getStr +“/g,’’);
str = str.replace(new RegExp(getStr,"g"),"");
if(oldStr.length-str.length > maxLength){
maxLength = oldStr.length-str.length;
result = getStr + "=" + maxLength;
}
}
return result;
}
5.闭包
var boxes = document.getElementsByTagName("div");
for(var i = 0; i < boxes.length; i++) {
boxes[i].index =i+1;//保存起来
boxes[i].onclick = function() {
alert(this.index);
}
}