1、添加对象属性值:
let obj = {a:'2',b:'3',c:'4'};
let index = 1;
obj[`top${index}`] = '5';
2、列表搜索,前端实现搜索:
// 模糊搜索
const list = [{name: '张三', age: '20', sex: '男', classNum: 2}, {name: '苏珊', age: '20', sex: '女', classNum: 2}]
const result = list.filter(item => item.age.includes('20'))
.filter(item => item.classNum === 2)
// 精确查找
const list = [{name: '张三', age: '20', sex: '男', classNum: 2}, {name: '苏珊', age: '20', sex: '女', classNum: 2}]
const result = list.find(item => item.name === '苏珊')
3、获取对象的属性值
const obj = {name: '张三', age: '20', sex: '男', classNum: 2}
const result = obj?.name
4、获取对象中所有属性值,并将多维数组展开成一个一维数组
const obj = {
'group1':[1,2,3],
'group2':[5,8,12],
'group3':[5,14,79],
'group4':[3,64,105],
}
const result = Object.values(obj).flat(Infinity)
// Object.values:获取对象所有的属性值,组成一个数组
// flat(): 用于将多维数组拉平(扁平化),不影响原数组,返回新的数组。
//仅有一个参数depth,用于指定拉平的深度,默认值为1。若depth指定为非正数,将返回原数组,指定为Infinity,无论多少层都将扁平化为一维数组。
5、if语句判断
if( test == 1 || test == 2 || test == 3 || test == 4){ }
//以上判断可以简写为
const condition= [1, 2, 3, 4]
const type = 1
if (condition.includes(type)) {
console.log('ok')
}
6、判断输入框不为空
const value = null
if(value !== null && value !== undefined && value !== ''){
//...
}
// 可以简写为
if((value??'') !== ''){
console.log('值不为空')
}else{
throw new Error('值是空的')
}
7、并发请求,使用Promise
const res = ()=>{
Promise.all([xxx,xxx]).then(([res1,res2])=>{
console.log(res1,res2)
})
}
8、使用new Set判断数组中是否存在不相等的值
// 使用场景:列表中存在多选操作,只能操作同一种状态的数据时
const arr = [
{name: '张三', age: '20', sex: '男', status: 'stop'},
{name: '苏珊', age: '18', sex: '女', status: 'enable'},
{name: '王五', age: '22', sex: '男', status: 'enable'}
]
if(new Set(arr.map(item=>item.status)).size !== 1){
console.log('存在status的值不相等的数据')
}
9、使用Object.assign()拷贝和合并对象
// 1、拷贝
let obj1 = {a:1,b:2,c:3};
let obj2 ={a:2,b:4,c:5,d:8};
let obj3 = Object.assign({}, obj1, obj2 );
// 2、合并
let obj1 = {a:1,b:2,c:3};
let obj2 ={a:2,b:4,c:5,d:8};
let obj3 = Object.assign(obj1, obj2 );
console.log(obj3); // {a:2,b:4,c:5,d:8}
// 3、合并数组
let arr1 = [{a:1,b:2,c:3}];
let arr2 = [{a:2.3,b:5,c:3,d:9}];
let arr3 = Object.assign([],arr1,arr2);
console.log(arr3); // [{a:2.3,b:5,c:3,d:9}]
10、记录一个js的数组新方法:arr.at()
at() 方法接收一个整数值并返回该索引的项目,允许正数和负数。负整数从数组中的最后一个项目开始倒数。
const group = [1,2,3];
group.at(0); // 1
group.at(-2); // 2
11、js方法:startsWith(), endsWith()
startsWith() 方法用于检测字符串是否以指定的子字符串开始,根据判断结果返回 true或false。
endsWith():用来判断当前字符串是否是以给定的子字符串结尾,根据判断结果返回 true 或 false。
const str = "Hello world, welcome to the Runoob.";
const n = str.startsWith("Hello");
console.log(n) // true
const end1 = str.endsWith("Hello");
console.log(end1) // false
const end2 = str.endsWith("Runoob.");
console.log(end2) // false