- 合并对象和数组(使用扩展运算符,合并数组考虑去重) ```vue const a = [1,2,3];
const b = [1,5,6];
const c = […new Set([…a,…b])]; //[1,2,3,5,6]
```vue
const obj1 = {
a:1,
}
const obj2 = {
b:1,
}
const obj = {...obj1,...obj2}; //{a:1,b:1}
- 拼接字符串
${}中可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。
const name = '小明';
const score = 59;
let result = '';
if(score > 60){
result = `${name}的考试成绩及格`;
}else{
result = `${name}的考试成绩不及格`;
}
const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;
- 判断条件优化(使用数组实例方法includes)
```vue const condition = [1,2,3,4];if(
type == 1 ||
type == 2 ||
type == 3 ||
type == 4 ||
){
//...
}
if( condition.includes(type) ){ //… }
4.列表搜索的精准搜索和模糊搜索(精准搜索用find找到后不会再遍历,节约性能,模糊搜索用filter)
```vue
const a = [1,2,3,4,5];
const result = a.find(
item =>{
return item === 3
}
)
- 数组扁平化
一个部门JSON数据中,属性名是部门id,属性值是个部门成员id数组集合,现在要把有部门的成员id都提取到一个数组集合中;获取对象的全部值要用Object.values,Infinity作为flat的参数可以使多维度数组扁平化; flat方法不支持IE浏览器;
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = [];
for (let item in deps){
const value = deps[item];
if(Array.isArray(value)){
member = [...member,...value]
}
}
member = [...new Set(member)]
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);
6.添加对象属性(给对象添加属性时,如果属性名是动态变化)
let obj = {};
let index = 1;
let key = `topic${index}`;
obj[key] = '话题内容';
let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';
7.输入框非空的判断(ES6中新出的空值合并运算符 ??’’)
if(value !== null && value !== undefined && value !== ''){
//...
}
if((value??'') !== ''){
//...
}