1.用对象优化if
function getComparisonTitle(strOperator) {
const operators = {
">": "大于",
">=": "大于等于",
"<": "小于",
"<=": "小于等于",
"==": "等于",
};
return operators[strOperator];
}
2.如何合并两个数组并删除重复项
用concat和filter:
const item1 = [2021, 2022, 2023];
const item2 = [2019, 2020, 2021];
const tmpItem = item1.concat(item2);
const newItem = tmpItem.filter((val, pos) => tmpItem.indexOf(val) === pos);
用set:
const newItem = [...new Set([...item1, ...item2])];
3.reduce
求和:
const arr=[1,2,3,4,5,6,7,8,9];
const res1=arr.reduce((res,value)=>{return res+value},0)
求积:
const res2=arr.reduce((res,value)=>{return res*value},1);
求最大值:
const res3=arr.reduce((res,value)=>{return res>value?res:value});
4.递归给每个都加1
var arr=[
1,
[2, 3],
[4, [5, 6, [7, 8]]]
]
function addOne(data){
data.forEach((item,index)=>{
Array.isArray(item)?addOne(item):data[index]=item+1
})
return data
}
addOne(arr)
5.对象数组排序
const objectArr = [
{ first_name: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a,b)=>a.last_name.localeCompare(b.last_name))
6.删除重复值
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// 输出: [5, 4, 7, 8, 9, 2]
7.合并多个对象
const summary = {...user, ...college, ...skills};
8.空合并算子
空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。
const foo = null ?? 'my school';
// 输出: "my school"
const baz = 0 ?? 42;
// 输出: 0
9.Rest & Spread 运算符
function myFun(a, b, ...manyMoreArgs) { return arguments.length;}myFun("one", "two", "three", "four", "five", "six");// 输出: 6
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
lyrics;
// 输出:
(5) ["head", "shoulders", "knees", "and", "toes"]
10.二维数组转一维数组
const array = [[1,2],[3,4]]
console.log(array.reduce((a,b) => a.concat(b)));
//[ 1, 2, 3, 4 ]
11.解构赋值的连续写法
//只解构出query
props({query}){
return {query.id,query.title}
}
//先解构出query,然后从query中解构出id,title
props({query:{id,title}}){
return {id,title}
}