// 字符串
// 字符串反转
// (split:字符串拆分为数组;reverse:反转数组;join:数组拼接为字符串)
let str1 = 'reverse string'
str1 = str1.split('').reverse().join('')
console.log('str1=', str1)
// 字符串查找
// indexOf、search(不同:indexOf:不能设置正则表达;search:没有第二次参数,不能从指定位置开始搜索)
let str = 'searchString'
let searStr = str.indexOf('Str')
let searStr1 = str.search('Str')
console.log('searStr=', searStr, searStr1)
// 提取字符串/截取字符串
// splic(start,end) 、subString(start,end) 、subStr(start,length)
let strText = 'strText'
let subStr = strText.slice(3, strText.length)
let subStr1 = strText.substring(3, strText.length)
let subStr2 = strText.substr(3, 4)
console.log('subStr=', subStr, subStr1, subStr2)
// 替换字符
// replace() 可使用正则匹配
let strText2 = 'replace text'
strText2 = strText2.replace('text', 'str')
console.log('strText2=', strText2)
// 字符转数组
// split() :参数为间隔符
// 数组方法
// 合并数组
// concat()
let arr1 = [1, 2]
let arr2 = [3, 4]
let andArr = arr1.concat(arr2)
console.log('andArr=', andArr)
// 数组重复元素
// 去重:[... new Set(arr)] (扩展运算符+set方法); Array.from + Set方法
let arr3 = [1, 1, 2, 2, 3, 4]
let dupArr = [... new Set(arr3)]
let dupArr1 = Array.from(new Set(arr3))
console.log('dupArr', dupArr, dupArr1)
// 获取重复元素
// es5:filter + indexOf ;es6:set + filter + has()
let arr4 = [1, 2, 3, 4, 5],
arr5 = [5, 6, 7, 8, 9]
let intersection = arr4.filter(function (val) { return arr5.indexOf(val) > -1 })
const arrSet1 = new Set(arr4),
arrSet2 = new Set(arr5)
let intersection1 = arr4.filter(item => arrSet2.has(item))
console.log('intersecition', intersection, intersection1)
// 翻转数组
// reverse()
let arr6 = [1, 2, 3, 4, 5, 6]
let revArr = arr6.reverse()
console.log('revArr=', revArr)
// 排序
let arr7 = [2, 45, 68, 12, 4]
// 冒泡排序
let sortArr = () => {
for (let i = 0; i < arr7.length; i++) {
for (let j = 0; j < arr7.length - i; j++) {
if (arr7[j] > arr7[j + 1]) {
[arr7[j], arr7[j + 1]] = [arr7[j + 1], arr7[j]]
}
}
}
return arr7
}
console.log('冒泡排序', sortArr(arr7))
// sort函数排序
let sortArr1 = arr7.sort((a, b) => {
return a - b;
})
console.log('sort函数排序', sortArr1)
let randomArr = [65, 12, 87, 12, 52]
// console.log('randomArr', randomArr)
// 快速排序
let quickSort = (arr) => {
if (arr.length <= 1) {
return arr;
}
let index = Math.floor(arr.length / 2)
let val = arr.splice(index, 1)
let leftArr = [],
rightArr = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] < val) {
leftArr.push(arr[i])
} else {
rightArr.push(arr[i])
}
}
return quickSort(leftArr).concat(val, quickSort(rightArr))
}
// console.log('快速排序', quickSort(randomArr))
console