本文章收集整理前端工作中的一些练手及提高编程水平的常规方法.
快速排序、冒泡排序、数组求和、数组个数统计
使用递归编写的快速排序方法
const { log } = console
const arr = [18, 12, 30, 14, 50, 16, 27, 89]
const quickSort = function (arr) {
if (arr.length < 2) {
return arr
}
let p = arr[0]
let low = arr.slice(1).filter(item=>item<=p)
let high = arr.slice(1).filter(item=>item>p)
return quickSort(low).concat([p]).concat(quickSort(high))
}
log(quickSort(arr)) //[12, 14, 16, 18,27, 30, 50, 89]
const { log } = console
const arr = [18, 12, 30, 14, 50, 16, 27, 89]
const bubbleSort = function (arr) {
if (arr.length < 2) {
return arr
}
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - 1; j++) {
// ES6写法
if (arr[j] > arr[j + 1]) {
[arr[j + 1], arr[j]] = [arr[j], arr[j+1]]
}
/*let tmp = ''
if (arr[j] > arr[j + 1]) {
tmp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tmp
}*/
}
}
return arr
}
log("冒泡排序:", bubbleSort(arr)) //冒泡排序: [12, 14, 16, 18,27, 30, 50, 89]
const { log } = console
const arr = [1,2,3,4,5,6]
const sumArr = function (arr) {
if (arr.length === 0) return 0
return arr[0] + sumArr(arr.slice(1))
}
log("数组求和:",sumArr(arr))// 21
const { log } = console
const arr = [1,2,3,4,5,6]
const sumArrWork = function (arr) {
return arr.reduce((prev, cur) => prev + cur);
}
log("工作中数组求和:",sumArrWork(arr)) // 21
const { log } = console
const arr = [1,2,3,4,5,6]
const countArr = function (arr) {
if (arr.length === 0) return 0
return 1 + countArr(arr.slice(1))
}
log("数组元素个数:",countArr(arr))// 6