冒泡排序
let Arr = [12, 34, 6, 32, 14, 77, 34, 12, 6, 4, 3]
function sort (arr) {
for (let i = 0
for (let j = 0
let num = arr[j + 1] - arr[j]
let temp
if (num < 0) {
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
}
sort(Arr)
console.log(Arr)
数组去重
let Arr = [2, 2, 4, 6, 78, 6, 34, 23, 13, 56]
function set (arr) {
let shuzu = []
Arr = arr.filter((item, index) => {
let bol = true
arr.forEach((item1, index1) => {
let a = item == item1
let b = index !== index1
if (a && b) {
bol = false
let c = shuzu.every((item3, index3) => {
return item != item3
})
if (c) {
shuzu.push(item)
}
}
})
if (!bol) {
}
return bol
})
arr = [...Arr, ...shuzu]
}
set(Arr)
console.log(Arr)
防抖
function fangdou(func, wait, immediate) {
let timer
return function () {
let _this = this
let arg = arguments
clearTimeout(timer)
if (immediate) {
let code = !timer
timer = setTimeout(function () {
timer = null
}, wait)
if (code) {
func.apply(_this, arg)
}
} else {
timer = setTimeout(function () {
func.apply(_this, arg)
}, wait)
}
}
}
树形数据
function formatTreeData (data) {
let parent = data.filter(item => item.pid === 0)
let children = data.filter(item1 => item1 !== 0)
toTreeData(parent, children)
function toTreeData (parent, children) {
parent.forEach(item2 => {
//循环子级
children.forEach((item3, index) => {
if (item2.id === item3.pid) {
let _children = JSON.parse(JSON.stringify(children))
_children.splice(index, 1)
toTreeData([item3], _children)
if (item2.children) {
item2.children.push(item3)
} else {
item2.children = [item3]
}
}
})
})
}
}