對象排重
var a = [{ id: 1 }, { id: 2 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 }]
var b = []
a.forEach((item, index) => {
var flag = true
b.forEach((it, i) => {
if (a[index].id == b[i].id) {
flag = false;
};
})
if (flag) {
b.push(a[index]);
};
})
console.log(b)
複製代碼
對象排序
var arr = [
{name:'zopp',age:0},
{name:'gpp',age:18},
{name:'yjj',age:8}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
console.log(arr.sort(compare('age')))
複製代碼
深淺拷貝
var data = {
list: [1, 2, 3, 4],
fn: function () {
alert(56789)
},
listdate: [
{
str: "8888"
}, {
arr: [{
txt: " al al al "
}]
}
]
}
function copy(data) {
var obj;
if (Object.prototype.toString.call(data) === '[object Object]') {
obj = {}
for (let key in data) {
if (typeof data[key] == "object") {
obj[key] = copy(data[key])
} else {
obj[key] = data[key]
}
}
} else if (Object.prototype.toString.call(data) === '[object Array]') {
obj = []
data.forEach((items) => {
if (typeof items == "object") {
obj.push(copy(items))
} else {
obj.push(items)
}
})
} else {
obj = data
}
return obj
}
var newDA = copy(data)
newDA.listdate[1].arr[0].txt = "jjjjjjj"
console.log(data.listdate[1].arr[0].txt)
console.log(newDA.listdate[1].arr[0].txt)
複製代碼
冒泡排序
var array=[10,20,9,8,79,65,100];
for ( var i=0;i<array.length-1;i++){
for (var j=0;j<array.length-1-i;j++) {
if (array[j] > array[j + 1]) {
var temp = array[i];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
console.log(array);
複製代碼
字符串中出現次數最多的一個字符
let testStr = 'asdasddsfdsfadsfdghdadsdfdgdasd';
function getMax(str) {
let obj = {};
for(let i in str) {
if(obj[str[i]]) {
obj[str[i]]++;
}else{
obj[str[i]] = 1;
}
}
let keys = Object.keys(obj);
let values = Object.values(obj);
let maxVal = Math.max(...values);
也可使用Math.max.apply(Math,values)可認爲是apply(Math.max, arr)
而後,arr是一個參數列表,對於max方法,其參數是若干個數,即Math.max(a, b, c, d, ...)
console.log(keys[values.indexOf(maxVal)],maxVal);
}
getMax(testStr);
複製代碼
函數防抖(debounce)
const _.debounce = (func, wait) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(func, wait);
};
};
複製代碼
函數節流(throttle)
const _.throttle = (func, wait) => {
let timer;
return () => {
if (timer) {
return;
}
timer = setTimeout(() => {
func();
timer = null;
}, wait);
};
};
複製代碼
二叉樹
function Node(data,left,right) {
this.data = data;
this.left = left;
this.right = right;
}
function BST(){
this.root = null;
this.insert = insert;
this.show = ()=>{
console.log(this.root);
}
}
function insert(data) {
let n = new Node(data,null,null);
if(this.root == null){
this.root = n;
}else{
let current = this.root;
let parent;
while(current){
parent = current;
if(data<current.data) {
current = current.left;
if(current == null) {
parent.left = n;
break;
}
}else{
current = current.right;
if(current == null){
parent.right = n;
break;
}
}
}
}
}
const bst = new BST();
bst.insert(13);
bst.insert(21);
bst.insert(15);
bst.insert(29);
bst.insert(3);
bst.insert(55);
bst.show();
複製代碼