codereview

116 阅读2分钟
  1. map()和forEach()的遍历方法使用区别
map有返回值,不需要重新定义一个变量。
#推荐用法:
http.get('url').then((res) => {
        this.productOptionsList = res?.result?.map((val) => {
          return {
            label: val.name,
            value: {
              appName: val.name,
              userName: ''
            }
          }
        })
      })
 #!不推荐
 const appObjs = []
        // 角色是管理员或者游客时,产品可以不选择
        this.addForm.appNames?.map(item => {
          let obj = {
            appName: item.appName || '',
            isDelete: 0,
            userName: this.addForm.roleName
          }
          appObjs.push(obj)
        })

  1. 适用于map,不适用于forEach,两者不混用。
this.addForm.roles?.forEach((item, index) => {
        this.addForm.roles[index].userName = this.addForm.userName
          item?.appObjs?.map((val, inx) => {
            this.addForm.roles[index].appObjs[inx].userName = this.addForm.userName
          })
      })
  1. splice增加
//删除 
 
 arr.splice(index, 1)  //指定下标删除 index指下标 1代表我只需要删除1个 
 
//增加
 arr.splice(index, 0, obj)  //index 指要增加元素的目标下标 obj要添加的元素 代表我不删除 
 
 
 
  1. 双层遍历可用递归写法
//不推荐写法
let paramsID = this.addForm.id ? 'update' : 'add'
      this.addForm.roles?.forEach((item, index) => {
        this.addForm.roles[index].userName = this.addForm.userName
          item?.appObjs?.map((val, inx) => {
            this.addForm.roles[index].appObjs[inx].userName = this.addForm.userName
          })
      })
 //推荐写法 递归 
const tree = [{
		name: "小红",
		children: [{
                    name: "小黄",
		    relation: "情侣",
		    children: [{
			name: "小绿",
			relation: "同学",
			children: [{
			name: "小青",
			relation: "同学"
			// ...
		}]

		}]
            }]
	}]
// 定义一个数组,用来存放处理后的数据
    var datalist = [];
   // 定义递归函数 里面的参数datas就是我们每次调用要处理的对象
	function recursion(datas) {
            // 循环每次的对象
	    for (let item of datas) {
                 // 如果它里面的children还是对象的话,就再调用一次这个函数
		// if (Array.isArray(item.children)) {
                    if (Array.isArray(item.children)) {
                    // 递归,这里的调用传入的参数都是每一层的children对象
                    doObj(item.children)
				}
			datalist.push({
                            name: item.name
			});
			// 跳出循环,避免重复push
			break;
		}
	}
	// 这里第一次调用,参数是整个对象
	recursion(tree)
	console.log(datalist)
  1. 根据id和pid把json结构 转 树状结构(转载)
const jsonData = [
    { id: '0', pid: '-1', name: '666' },
    { id: '4', pid: '1', name: '大家电' },
    { id: '5', pid: '1', name: '生活电器' },
    { id: '1', pid: '0', name: '家用电器' },
    { id: '2', pid: '0', name: '服饰' },
    { id: '3', pid: '0', name: '化妆' },
    { id: '7', pid: '4', name: '空调' },
    { id: '8', pid: '4', name: '冰箱' },
    { id: '9', pid: '4', name: '洗衣机' },
    { id: '10', pid: '4', name: '热水器' },
    { id: '11', pid: '3', name: '面部护理' },
    { id: '12', pid: '3', name: '口腔护理' },
    { id: '13', pid: '2', name: '男装' },
    { id: '14', pid: '2', name: '女装' },
    { id: '15', pid: '7', name: '海尔空调' },
    { id: '16', pid: '7', name: '美的空调' },
    { id: '19', pid: '5', name: '加湿器' },
    { id: '20', pid: '5', name: '电熨斗' },
    { id: '21', pid: '20', name: '电熨斗子项' },
];

/**
 * 根据id和pid把json结构 转 树状结构
 * @param  jsonArr  {json}      json数据
 * @param  idStr  {String}    id的属性名
 * @param  pidStr  {String}    父id的属性名
 * @param  childrenStr  {String}    children的属性名
 * @return  {Array}     数组
 */
const transData = (jsonArr, idStr, pidStr, childrenStr) => {
    // 存放的最终结果树数组
    const result = [];
    const id = idStr;
    const pid = pidStr;
    const children = childrenStr;
    const len = jsonArr.length;

    // 遍历得到以id为键名的对象(建立整棵树的索引)
    const hash = {};
    jsonArr.forEach(item => {
    		 hash[item[id]] = item;
    });

    for (let j = 0; j < len; j++) {
        const jsonArrItem = jsonArr[j];
        const hashItem = hash[jsonArrItem[pid]];
        if (hashItem) {
            // 如果当前项还没有children属性,则添加该属性并设置为空数组
            !hashItem[children] && (hashItem[children] = []);
            hashItem[children].push(jsonArrItem);
        } else {
            result.push(jsonArrItem);
        }
    }
    return result;
};

const jsonDataTree = transData(jsonData, 'id', 'pid', 'children');
console.log(jsonDataTree)

  1. 数据兜底
addFormList() {
      return this.addForm.roles?.filter(item => item.isDelete !== 1)
    }
http.get('url').then((res) => {
   this.roleIds = res.result.roleIds || ['TOURIST']
   this.tabNames = res.result.tabNames || []
   this.activeName = res.result.tabNames?.[0] // tabNames可能为空数组
  1. 清空参数的简单方法 直接设置某些参数值为undefined
let paramsID = this.addForm.id ? 'update' : 'add'
      const keysList = Object.keys(this.addForm)
      keysList.includes('appNames') && delete this.addForm.appNames
      keysList.includes('roleTempId') && delete this.addForm.roleTempId
      this.addForm.roles?.forEach((item, index) => {
        this.addForm.roles[index].userName = this.addForm.userName
          item?.appObjs?.map((val, inx) => {
            this.addForm.roles[index].appObjs[inx].userName = this.addForm.userName
          })
      })
  // 推荐写法
  this.addForm.appNames = undefined
  this.addForm.roleTempId = undefined