js常用方法-笔记

1.数组去重

/*  
功能 去重
参数 arr 原数组
	item 对object中的某个字段进行去重
*/
function unique(arr,item=null) {
	for(let i = 0; i < arr.length; i++){
		for(let j = i + 1; j < arr.length; j++){
			if(item) {
				if(arr[i][item] === arr[j][item]){
					arr.splice(j, 1); // 移除重复元素
					j--; // 修正下标
				}
			}else {
				if(arr[i] === arr[j]){
					arr.splice(j, 1); // 移除重复元素
					j--; // 修正下标
				}
			}
		}
	}
	return arr;
};
let arr = [{item:1},{item:1},{item:2},{item:2},{item:3},{item:4}]
console.log(unique(arr,'item')) // [{item:1}{item:2},{item:3},{item:4}]

2.模糊查询

/* 
	功能:模糊查询
	参数:list 需要查询的列表数据 Array
		 item 需要查询的字段    String
		 name 需要查询的内容    String
*/
function fuzzyQuery(list,item,name) {
	var arr = [];
	var reg = new RegExp(name);
	for(var i = 0; i < list.length; i++) {
		if(reg.test(list[i][item])) {
			arr.push(list[i])
		}
	}
	return arr;
}
var list = [{name:'张一一'},{name:'张三三'},{name:'李三三'}]
console.log(fuzzyQuery(list,'name','三三')) // [{name:'张三三'},{name:'李三三'}]

3.数组排序

/* 
	功能:数组排序
	参数:arr 原数组 (array)
		 item 根据对象中的 某个字段 进行排序 (string)
*/
function sorting(arr,item = null) {
	if(item) {
		for(var i = 0; i < arr.length - 1; i++) {
			for(var j = 0; j < arr.length - 1 - i; j++) {
				if(arr[j][item] > arr[j+1][item]) {
					var temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}
	}else {
		for(var i = 0; i < arr.length - 1; i++) {
			for(var j = 0; j < arr.length - 1 - i; j++) {
				if(arr[j] > arr[j+1]) {
					var temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}
	}
	return arr;
}
var arr = [{num:1},{num:6},{num:3},{num:5}];
console.log(sorting(arr,num)) // [{num:1},{num:3},{num:5},{num:6}];

4.排序

//数字类型排序
let arr = [{item: 2},{item: 1},{item: 3}];
arr.sort((a,b) => a.item - b.item); //[{item: 1},{item: 2},{item: 3}];

//字母类型排序
let arr = [{item: 'B'},{item: 'A'},{item: 'C'}];
arr.sort((a, b) => a.item.charCodeAt() - b.item.charCodeAt())
//[{item: 'A'},{item: 'B'},{item: 'C'}];

5.取出数组中相同类型数据生成集合

let arr = [
	{name: '张三', label: 'Z'},
	{name: '李四', label: 'L'},
	{name: '张显圣', label: 'Z'},
	{name: '张无忌', label: 'Z'},
	{name: '刘晓冉', label: 'L'},
	{name: '白先生', label: 'B'},
]

//如需排序
arr.sort((a, b) => a.label.charCodeAt() - b.label.charCodeAt())
let obj = {};

arr.map(item => {
	if(!obj[item.label]) {
		obj[item.label] = [item]
	} else {
		obj[item.label].push(item)
	}
})
console.log(obj)
// {"B":[{"name":"白先生","label":"B"}],"L":[{"name":"李四","label":"L"},{"name":"刘晓冉","label":"L"}],"Z":[{"name":"张三","label":"Z"},{"name":"张显圣","label":"Z"},{"name":"张无忌","label":"Z"}]}

6.生成时间段列表

/* 
	功能: 获取时间段列表
	参数:startTime: 开始时间 (8:00)
		 endTime:结束时间 (18:00)
		 interval:时间间隔(分钟) 
		 splice: 裁剪 传true裁剪掉超出结束时间的item,false为不裁剪,默认false
 */
function getTimeList(startTime,endTime,interval,splice) {
	let timeList = [];
	let startDate = new Date().setHours(startTime.split(':')[0],startTime.split(':')[1]);
	let endDate = new Date().setHours(endTime.split(':')[0],endTime.split(':')[1]);
	let count = (endDate - startDate) / 1000 / 60 / interval;
	let date = new Date(startDate);
	for(let i = 0; i < count; i++) {
		timeList.push({});
		timeList[i].startTime = date.getHours() + ':' + (date.getMinutes() > 9? date.getMinutes() : ('0' + date.getMinutes()));
		date.setMinutes(date.getMinutes() + interval);
		timeList[i].endTime = date.getHours() + ':' + (date.getMinutes() > 9? date.getMinutes() : ('0' + date.getMinutes()));
	}
	if(splice){
		for(var i = 0; i < timeList.length; i++) {
			if(timeList[i].endTime > endTime) {
				timeList.splice(i,1)
			}
		}
	}
	return timeList;
}
console.log(getTimeList('8:00','18:00',30)) // [{startTime: '8:00',endTime: '8:30'},{startTime: '8:30',endTime: '9:00'},......{startTime:'17:30',endTime:'18:00'}]

7.超出规定字节后显示省略号

/** 
	@功能:超出规定字节后显示省略号
	@参数:str 原始字符串
		 num 字节数,超出后拼接省略号
	@return 拼接后的字符串
 */
function getByteLen(str, num){
  let len=0;
	let arr = [];
  for(let i=0;i<str.length;i++){
    str.charCodeAt(i)<256?(len+=1):(len+=2)
		arr.push(str[i])
		if(len >= num) break;
  }
  return arr.join('') + '...';
}

8.使html字符串中图片的宽高自适应

function formatRichText(html) {
  let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi,'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
  return newContent;
            
}

9.一维数组转二维数组

function formatArr(arr, num) {
  let newArr = []
  const total = Math.ceil(arr.length / num)
  for (let i = 0; i < total; i++) {
     a = arr.slice(i * num, (i + 1) * num)
     newArr.push(a)
  }
  return newArr
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8]
console.log(formatArr(arr, 4));

10.elementUI 树形表格更新子节点数据

refreshRow(pId){ //在新增、删除子节点时调用,参数为父节点的id
	listClassify({pId: id}).then(res => { //请求子节点数据
		if(res.data.length) {
			 res.data.forEach(item => {
			   item.level = this.form.level;
			 })
		}
		//lazyTreeNodeMap-table实例中的store.states.lazyTreeNodeMap
		//pId需要更新子节点的pid
		//需要更新子节点的数据
		this.$set(this.$refs.table.store.states.lazyTreeNodeMap, pId, res.data)
	})
			
},

11.获取url后面的参数

new URLSearchParams(window.location.search).get('参数名')

12.解决若依上传图片多选不生效的问题

 handleUploadSuccess(res, file, fileList) {
      // this.fileList.push({ name: res.fileName, url: res.url });  //old
 
      if(fileList.every(it => it.status == 'success')) { //等待所有文件都上传完成,这里注意fileList是所有的文件(包含已上传的)
        fileList.map(item => {
          item.response && this.fileList.push({ name: item.response.fileName, url: item.response.url }); //只push新上传的 (带有response)
        })
        console.log(fileList, this.fileList);
        this.$emit("input", this.listToString(this.fileList));
        this.loading.close();
      }
    },
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾里桃花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值