遍历数组与对象的函数
function Foreach(obj,fn){
var key;
if(obj instanceof Array){
obj.forEach((item,index)=>{
fn(index,item);
})
}else{
for(key in obj){
fn(key,obj[key]);
}
}
}
// var obj = {x:100,y:900};
// Foreach(obj,(key,value)=>{console.log(key,value)});
var arr = [66,77,33]
Foreach(arr,(index,item)=>{console.log(index,item)});
获取2020-12-23格式的日期
方法1. function getTime(ti){
if(!ti){
ti = new Date();
}
let year = ti.getFullYear();
let month = ti.getMonth()+1;
let date = ti.getDate();
if(month < 10){
month = '0' + month;
}
if(date < 10){
date = '0' + date;
}
return year + '-' + month + '-' + date;
}
let ti = new Date();
let formatDate = getTime(ti) //"2020-12-23"
方法2. let time = new Date().toISOString().slice(0,10);
查找url参数
const url = 'http://erp.yang800.cn/my-store/1609847898208?config_id=1604303484505114&page_title=%E6%88%91%E7%9A%84%E5%BA%97%E9%93%BA';
1.输入参数名获取值
function fn(url ,name){
let search = url.slice(1);
let param = search.split('&');
for(let i = 0;i < param.length ;i++){
var q = param[i].split('=');
if(q[0] == name){
return decodeURIComponent(q[1]);
}
}
}
console.log(fn(url , 'page_title'));
2.url解析为js对象
function getUrlParams() {
let search = window.location?.hash?.split('?')[1];
let list = search?.split('&');
let res = {};
list?.forEach(val => {
let q = val.split('=');
res[q[0]] = decodeURIComponent(q[1]);
})
return res;
}
3.url解析为js对象
function getUrlParams() {
const res = {};
const list = new URLSearchParams(location.search);
list.forEach((val, key) => {
res[key] = decodeURIComponent(val);
})
}
4.输入参数名获取值
function query(url, name){
const param = new URLSearchParams(url);
return param.get('name');
};
query(url, "name")
3.RegExp
const reg = new RegExp(`(^|&)${name}=(([^&]*)(&|$))`,'i');
防抖
用户输入暂停100ms才搜索
用户搜索时快速输入 1、2 输入 1 时触发debounce函数的定时器时间没到还未执行
立即输入 2 了,就把 1 触发的setTimeout清除,执行2的定时器,也就达到了重新计时
function debounce(fn, delay) {
let time = null;
return function () {
if (time) {
clearTimeout(time);
}
time = setTimeout(() => {
fn.apply(this, arguments)
time = null
},delay)
}
}
节流
类似技能冷却,一直拖动方块获取坐标值也就会一直触发throttle函数,只需要在200ms执行一次
function throttle(fn, delay) {
let time = null
return function () {
if (time) {
return ;
}
time = setTimeout(() => {
fn.apply(this, arguments)
time = null
}, delay)
}
}
向字符串中添加一个字符
let str = text.split('')
str.splice(4,0,'-')
let date = str.join('');
递归
1.阶层
5 * 4 * 3 * 2 * 1
function jc(n){
if(n == 1 || n == 0){
return 1;
}
return n*jc(n - 1)
}
//用一个数组存储值
var fb = function () {
var memo = [0, 1];
var fib = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
}
return fib
}()
2.斐波拉契数列
1 1 2 3 5 8 13
function fb(n){
if(n == 1 || n == 2){
return 1;
}
return fb(n - 1) + fb(n - 2)
}
数组乱序排列
list.sort(function(){ return Math.random() -0.5 })
获取随机数,要求是长度一致的字符串格式
let num = Math.random() * 1000;
num += '';
let newNum = num.slice(0,6);
数组拍平
flat(Infinty)
set 无序,不能重复
function unique(arr){ const set = new set(arr); return [...set] }; unique(11,22,33,44,11);
数据打乱重拍
let nums = [1,2,3,4,5,6];
function mySort(_nums){
let nums = [..._nums]
let arr = []
while(arr.length < nums.length){
let index = parseInt(Math.random() * nums.length);
if(nums[index]){
arr.push(nums[index]);
nums[index] = null;
}
}
console.log(arr);
}
function mySort2(_nums){
let nums = [..._nums]
let arr = []
while(nums.length > 0){
let index = parseInt(Math.random() * nums.length);
arr.push(nums[index]);
nums.splice(index,1)
}
console.log(arr);
}
nums.sort(() => Math.random() - Math.random())
获取当前时间
getTime() {
let weeks = ['天', '一', '二', '三', '四', '五', '六'];
let myTime = new Date();
let year = myTime.getFullYear();
let month = myTime.getMonth() + 1;
let day = myTime.getDate();
let week = myTime.getDay();
let hours = myTime.getHours();
let minutes = myTime.getMinutes();
let seconds = myTime.getSeconds();
let timeStr = '今天是:' + year + '年' + month + '月' + day + '日 星期' + weeks[week] + hours + '时' + minutes + '分' + seconds + '秒';
}
获取当前实时时间
<div id="currentTime"></div>
data() {
return {
timer: null
}
}
created() {
let timer = setInterval(() => {
this.fnDate();
}, 1000);
// 离开当前页面时销毁定时器
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
this.timer = null;
})
},
//js 获取当前时间
fnDate() {
let oDiv = document.getElementById("currentTime");
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let data = date.getDate();
let hours = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
let time = year + "-" + this.fnW((month + 1)) + "-" + this.fnW(data) + " " + this.fnW(hours) + ":" + this.fnW(minute) + ":" + this.fnW(second);
let a = new Array("日", "一", "二", "三", "四", "五", "六");
let week = new Date().getDay();
let str = "星期" + a[week];
oDiv.innerHTML = time + " " + str;
},
//补位 当某个字段不是两位数时补0
fnW(str) {
return str > 9 ? str : "0" + str;
},