常用的js开发技巧

本文提供了一系列JavaScript实用代码,包括时间比较、金钱格式化、随机ID生成等,适用于前端开发人员快速解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 比较时间大小
	const time1 = "2019-02-14 21:00:00";
	const time2 = "2019-05-01 09:00:00";
	const overtime = time1 > time2;
	// overtime => false
	或者:
    compareDate(date1, date2) {
      var oDate1 = new Date(date1)
      var oDate2 = new Date(date2)
      if (oDate1.getTime() > oDate2.getTime()) {
        return true //第一个大
      } else {
        return false //第二个大
      }
    },
    或者
    compareTime(time) {
      return time.replace(/:/g, '')
    },
  1. 格式化金钱
	const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	const money = ThousandNum(20190214);
	// money => "20,190,214"
  1. 生成随机字母ID
	const RandomId = len =>Math.random().toString(36).substr(3, len);
	const id = RandomId(10);
	// id => "jg7zpgiqva"
  1. 生成随机HEX色值
	const RandomColor = () =>"#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
	const color = RandomColor();
	// color => "#f03665"
  1. 生成星级评分
	const StartScore = rate =>"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
	const start = StartScore(3);
	// start => "★★★"
  1. 操作URL查询参数
	const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?	name=young&sex=male"
	params.has("young"); // true
	params.get("sex"); // "male"
  1. 克隆数组和对象、合并
	const _arr = [1,2]; 
	const arr = [..._arr];
	const _obj = { a: 0, b: 1, c: 2 };
	const obj = { ..._obj };
	const obj = { ...obj1, ...obj2 };
	//对象深拷贝
	function deepClone(obj){
	    let objClone = Array.isArray(obj)?[]:{};
	    if(obj && typeof obj==="object"){
	        for(key in obj){
	            if(obj.hasOwnProperty(key)){
	                //判断ojb子元素是否为对象,如果是,递归复制
	                if(obj[key]&&typeof obj[key] ==="object"){
	                    objClone[key] = deepClone(obj[key]);
	                }else{
	                    //如果不是,简单复制
	                    objClone[key] = obj[key];
	                }
	            }
	        }
	    }
	    return objClone;
	}    

  1. 满足条件时执行
	const flagA = true; // 条件A
	const flagB = false; // 条件B
	(flagA || flagB) && Func(); // 满足A或B时执行
	(flagA || !flagB) && Func(); // 满足A或不满足B时执行
	flagA && flagB && Func(); // 同时满足A和B时执行
	flagA && !flagB && Func(); // 满足A且不满足B时执行
  1. 数组去重
	const arr = [...new Set([0, 1, 1, null, null])];
	// arr => [0, 1, null]
  1. 过滤空值:undefined、null、""、0、false、NaN
	const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
	// arr => [1, 2]
  1. 清空数组
	const arr = [0, 1, 2];
	arr.length = 0;
	// arr => []```
  1. 统计数组成员个数
	const arr = [0, 1, 1, 2, 2, 2];
	const count = arr.reduce((t, v) => {
		t[v] = t[v] ? ++t[v] : 1;
		return t;
	}, {});
	// count => { 0: 1, 1: 2, 2: 3 }
  1. 解构数组成员嵌套
	const arr = [0, 1, [2, 3, [4, 5]]];
	const [a, b, [c, d, [e, f]]] = arr;
	// a b c d e f => 0 1 2 3 4 5```
  1. 自适应页面(页面基于一张设计图但需做多款机型自适应,元素尺寸使用rem进行设置)
	function AutoResponse(width = 750) {
	    const target = document.documentElement;
	    target.clientWidth >= 600
	        ? (target.style.fontSize = "80px")
	        : (target.style.fontSize = target.clientWidth / width * 100 + "px");
	}
	或者:
	var calculatSeize = function () {
	    var BASE_FONT_SIZE = 100;
	    var roat =1;
	    var docEl = document.documentElement,
	        clientWidth = docEl.clientWidth;
	        clientHeight = docEl.clientHeight;
	    if (!clientWidth) return;
	    var html_font_size = BASE_FONT_SIZE * ((clientWidth*roat) / 750);
	    docEl.style.fontSize = html_font_size+'px';
	    if (html_font_size-parseFloat(getComputedStyle(docEl).fontSize)<0.01&&html_font_size-parseFloat(getComputedStyle(docEl).fontSize)>-0.01) {
	        return;
	    } 
	    else {
	        var again_html_font_size = html_font_size/(parseInt(getComputedStyle(docEl).fontSize)/html_font_size);
	        docEl.style.fontSize = again_html_font_size + 'px';
	    }
	};
	if (document.addEventListener) {
	    var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
	    window.addEventListener(resizeEvt, calculatSeize, false);
	    document.addEventListener('DOMContentLoaded', calculatSeize, false);
	    calculatSeize();
	}

15.存取LocalStorage(反序列化取,序列化存)

	const love = JSON.parse(localStorage.getItem("love"));
	localStorage.setItem("love", JSON.stringify("I Love You"))```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值