一、过滤 filter
let arr = [1, 2, 3, 4, 5, 6]
const newArr = arr.filter(item => {
return item > 3
})
console.log('Arr', newArr)
二、排序 sort
let arr = [1, 2, 3, 4, 5, 6]
let obj = [
{ id: 12, name: 'tom' },
{ id: 2, name: 'lin' },
{ id: 24, name: 'sun' },
]
const newArr = arr.sort((a, b) => a - b) //升序
const newObj = obj.sort((a, b) => b.id - a.id) //降序
console.log('Arr,Obj', newArr, newObj)
三、去除数组指定元素 splice(元素开始,删除个数)
let arr = [1, 2, 3, 4, 5, 6]
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 3) {
arr.splice(i, 1)
i-- //重点
}
}
console.log('Arr', arr)
四、数组的元素全部符合条件返回true every
let obj = [
{ id: 12, name: 'tom' },
{ id: 2, name: 'lin' },
{ id: 24, name: 'sun' },
]
const newObj = obj.every(item => {
return item.id > 10
})
console.log('Obj', newObj)
五、数组的元素任一项符合条件返回true some
let obj = [
{ id: 12, name: 'tom' },
{ id: 2, name: 'lin' },
{ id: 24, name: 'sun' },
]
const newObj = obj.some(item => {
return item.id > 22
})
console.log('Obj', newObj)
六、处理错误(保证方法继续执行)
function handleError() {
const string = 'HelloCsdn'
try {
console.log(string.join(','))
} catch (error) {
console.log(error)
}
console.log('继续执行')
}
handleError();
七、合并对象(浅拷贝)
let user_info = {
name:'cc',
age:12
}
let user_activity = {
dec:'playGame',
date:'4.27'
}
//括号前面写一个空的{},防止污染第一个对象
const arr3 = Object.assign({},user_info,user_activity)
//第二种
const arr4 = [...user_info,...user_activity]
八、将url字符串转换成对象
var parseQuery = function (query) {
var reg = /([^=&\s]+)[=\s]*([^&\s]*)/g;
var obj = {};
while (reg.exec(query)) {
obj[RegExp.$1] = RegExp.$2;
}
return obj;
}
===============调用方式===============
parseQuery('params1=123¶ms2=10¶ms3=cc')
结果:
params1: "123"
params2: "10"
params3: "cc"
九、数组元素交换位置
let params = [1,2,3,4,5]
function exchange(arr,index1,index2) {
return arr[index2] = arr.splice(index1,1,arr[index2])[0]
}
exchange(params,0,3)
console.log('params', params);