js 数组中搜索元素

1、some()

检测数组中的元素是否满足指定条件,如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。

如果没有满足条件的元素,则返回false。不会对空数组进行检测。不会改变原始数组。

 // 方法一
 const arr = [ { id: 1, username: 'red' }, { id: 2, username: 'green' }, { id: 2, username: 'blue' } ];
 ​
 function add(arr, name) {
   const { length } = arr;
   const id = length + 1;
   const found = arr.some(el => el.username === name);
   if (!found) arr.push({ id, username: name });
   return arr;
 }
 ​
 console.log(add(arr, 'testname'));
 ​
 // 方法二
 const newUser = {_id: 4, name: 'Adam'}
 const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]
 ​
 const userExists = users.some(user => user.name === newUser.name);
 if(userExists) {
     return new Error({error:'User exists'})
 }
 users.push(newUser)
 ​
 // 这里和上面一样some方法判断是否存在
 const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
 const checkUsername = obj => obj.name === 'max';
 console.log(arrayOfObject.some(checkUsername))

 

2、 .filter 箭头函数

这里我使用带有 .filter 的 ES6 箭头函数来检查新添加的用户名是否存在。(filter 返回符合条件的新数组,原数组不变。不会对空数组进行检测。)

 var arr = [{
     id: 1,
     username: 'fred'
 }, {
     id: 2,
     username: 'bill'
 }, {
     id: 3,
     username: 'ted'
 }];
 ​
 function add(name) {
  var id = arr.length + 1;        
      if (arr.filter(item=> item.username == name).length == 0){
      arr.push({ id: id, username: name });
    }
 }
 add('ted');
 console.log(arr);

 

3、request样式范例

 
 export function getSumDataRain(params) {  //获取过程雨量列表
     return request({
         url: '/rtdata/getSumDataRain',
         method: 'get',
         params:params
     })
 }
 export function publishYJXY(params){  //获取防汛响应等级
     return request({
         url: '/Fxyw/publishYJXY',
         method: 'post',
         data:params,
     })
 }
 export function addPlanFile(formData,headers) {  //上传pdf
     return request({
         url: '/tactics/upload',
         method: 'post',
         headers:headers,
         data: formData
     })
 }

 

 
 
posted @ 2025-06-17 09:30  Bordery  阅读(27)  评论(0)    收藏  举报