项目中可能用到的一些方法
数组需要逐个发起请求
async function dbFuc(db) { let docs = [{}, {}, {}]; // 报错 docs.forEach(function (doc) { await db.post(doc); }); } --------------- async function dbFuc(db) { let docs = [{}, {}, {}]; let promises = docs.map((doc) => db.post(doc)); let results = await Promise.all(promises); console.log(results); } // 或者使用下面的写法 async function dbFuc(db) { let docs = [{}, {}, {}]; let promises = docs.map((doc) => db.post(doc)); let results = []; for (let promise of promises) { results.push(await promise); } console.log(results); }
进度条的显示
async function loadUser(users){ for(let i = 0; i<users.length; i++){ let user = await query(user[i]) let progess = (i + 1) /users.length * 100 loading.style.width = progress + '%' loading.innerHTML = Math.round(progress) + '%' } } loadUser(['用户1', '用户2', '用户3'])
var users = [
{ username: 'JX01', status: 'offline' },
{ username: 'yazeedBee', status: 'online' },
]
var arrayIntoObject = (key, list) =>
list.reduce((acc, obj) => {
const value = obj[key];
acc[value] = obj;
return acc
}, {})
arrayIntoObject('username', users)
1.
(1)获取url的查询参数代码 ' ?foo = bar&baz = bing ' 期望得到 { foo: bar, baz: bing }
var url = '?foo=bar&baz=bin' var q={} url.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v)
console.log(q) // {foo: "bar", baz: "bin"}
(2)获取url里面的参数值或者追加查询字符串
假如我们有这样一个url,"?post=1234&action=edit",可以这样处理这个url
var urlParams = new URLSearchParams('?post=1234&action=edit'); console.log(urlParams.has('post')); // true console.log(urlParams.get('action')); // "edit" console.log(urlParams.getAll('action')); // ["edit"] console.log(urlParams.toString()); // "?post=1234&action=edit" console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
(3) 去除前后空格
function trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); }
2.函数直接赋值一个函数,如果没有传参,我们就直接抛出错误提醒,如果一个组件里面有很多方法,我们就可以直接复用,而不用每个方法里面都去做非空判断处理
const isRequired = () => { throw new Error('param is required'); }; const hello = (name = isRequired()) => { console.log(`hello ${name}`) }; // 抛出一个错误,因为没有参数没有传 hello(); // 没有问题 hello('hello')
3.document.scrollingElement控制窗体滚动高度,一统江湖
(document.documentElement.scrollTop PC端) (document.body.scrollTop 移动端)
希望页面滚动定位到具体位置的时候,如400像素,直接一行代码就可以搞定了:document.scrollingElement.scrollTop = 400;
4.var str = '1231344023211312.0078' 小数点开始 每隔三个数加上 逗号 => 1,231,344,023,211,312.0078
var str = '1231344023211312.0078'.replace(/(?=(?!^)(?:\d{3})+(?:\.|$))(\d{3}(\.\d+$)?)/g,',$1'); console.log(str)
5.生成随机ID (10位数)
// 生成随机ID (10位数)
const randomId = len => Math.random().toString(36).substr(3, len); const id = randomId(10); console.log(id)
---------------------------
// 获取随机数组成员
var arr = [0, 1, 2, 3, 4, 5];
var randomItem = arr[Math.floor(Math.random() * arr.length)];
console.log(randomItem)
6.当对输入框里面的值做判断时候,转数值:只对 ‘ ’, null,false 有效,比如在 i f 判断
var num1 = +null; var num2 = +""; var num3 = +false; var num4 = +"10"; var num5 = undefined if(!+num4) console.log('66666')
7.异步累计
async function Func(deps) { return deps.reduce(async(t, v) => { const dep = await t; const version = await Todo(v); dep[v] = version; return dep; }, Promise.resolve({})); } const result = await Func(); // 需在async包围下使用
xx.业务逻辑代码配置优化
var listWarnConf = [ {warnType: 1, warnCondition: 220}, {warnType: 2, warnCondition: 36}, {warnType: 3, warnCondition: 45}, {warnType: 4, warnCondition: 110}, {warnType: 5, warnCondition: 380} ] // 可能如下一顿操作 listWarnConf.forEach(item => { switch(item.warnType) { case 1: item.warnTypeText = '超压'; item.warnConditionText = `电压高于${item.warnCondition}V` break; case 2: item.warnTypeText = '欠压'; item.warnConditionText = `电压低于${item.warnCondition}V` break case 3: item.warnTypeText = '超载'; item.warnConditionText = `电流高于${item.warnCondition}A` break case 4: item.warnTypeText = '电压不平衡'; item.warnConditionText = `电压不平衡高于${item.warnCondition}%` break case 5: item.warnTypeText = '电流不平衡'; item.warnConditionText = `电流不平衡${item.warnCondition}%` break } })
优化
//配置数据 var warnConfig={ 1:{ warnTypeText:'超压', warnConditionText:'电压高于replaceTextV' }, 2:{ warnTypeText:'欠压', warnConditionText:'电压低于replaceTextV' }, 3:{ warnTypeText:'超载', warnConditionText:'电流高于replaceTextV' }, 4:{ warnTypeText:'电压不平衡', warnConditionText:'电压不平衡高于replaceText%' }, 5:{ warnTypeText:'电流不平衡', warnConditionText:'电流不平衡高于replaceText%' } } // 一顿操作 listWarnConf.forEach(item => { item.warnTypeText=warnConfig[item.warnType].warnTypeText; item.warnConditionText=warnConfig[item.warnType].warnConditionText.replace('replaceText',item.warnCondition); })
8. 给个数字num = 5, 计算出卖家评价给的星星数。
即 var num = 5
输出 var arr = [{"label": 1, "val": 1}, {"label": 2, "val": 2}, {"label": 3, "val": 3}, {"label": 4, "val": 4}, {"label": 5, "val": 5}]
var num = 5 var res = Array.from({length: num}, (item, index)=>{ return {label: index + 1, val: index +1} }) console.log(JSON.stringify(res, null, 2))
9.取出对象中某些想要的属性
var object = { a: 5, b: 6, c: 7 };
输出 var res = { a: 5, c: 7 }
var object = { a: 5, b: 6, c: 7 }; var picked = (({ a, c }) => ({ a, c }))(object); console.log(picked); // { a: 5, c: 7 }
10. Map转为对象
如果所有的Map的key值都是字符串,它可以转为对象
function strMapToObj(strMap) { let obj = Object.create(null); for (let [k, v] of strMap) { obj[k] = v; } return obj; } let myMap = new Map().set('yes', true).set('no', false); strMapToObj(myMap); // { yes: true, no: false }
对象转为Map
function objToStrMap(obj) { let strMap = new Map(); for (let k of Object.keys(obj)) { strMap.set(k, obj[k]); } return strMap; } objToStrMap({ yes: true, no: false }); // [ [ 'yes', true ], [ 'no', false ] ]
11.使用~~双为操作符来代替证书的 Math.floor,执行相同的操作符运行速度更快
Math.floor(4.9) === 4 //true
// 简写为:
~~4.9 === 4 //true
12.数组对象转 对象
var cities = [ { name: 'Paris', visited: 'no' }, { name: 'Lyon', visited: 'no' }, { name: 'Marseille', visited: 'yes' }, { name: 'Rome', visited: 'yes' }, { name: 'Milan', visited: 'no' }, { name: 'Palermo', visited: 'yes' }, { name: 'Genoa', visited: 'yes' }, { name: 'Berlin', visited: 'no' }, { name: 'Hamburg', visited: 'yes' }, { name: 'New York', visited: 'yes' } ]; var result = cities.reduce((accumulator, item) => { return { ...accumulator, [item.name]: item.visited } }, {}); console.log(result);
----------------------------------------
const cities = [
{ name: 'Paris', visited: 'no' },
{ name: 'Lyon', visited: 'no' },
{ name: 'Marseille', visited: 'yes' },
{ name: 'Rome', visited: 'yes' },
{ name: 'Milan', visited: 'no' },
{ name: 'Palermo', visited: 'yes' },
{ name: 'Genoa', visited: 'yes' },
{ name: 'Berlin', visited: 'no' },
{ name: 'Hamburg', visited: 'yes' },
{ name: 'New York', visited: 'yes' }
];
const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
// outputs ["Paris", "Lyon", "Marseille", "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]
---------------------
有条件的对象属性
nst getUser = (emailIncluded) => {
return {
name: 'John',
surname: 'Doe',
...emailIncluded && { email : 'john@doe.com' }
}
}
const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }
const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }
---------------
对象包含很多属性,有时只需要其中的几个,使用解构来提取
var rawUser = {
name: 'John',
surname: 'Doe',
email: 'john@doe.com',
displayName: 'SuperCoolJohn',
joined: '2016-05-05',
image: 'path-to-the-image',
followers: 45
}
var user = {}, userDetails = {};
({ name: user.name, surname: user.surname, ...userDetails } = rawUser);
console.log(user); // outputs { name: "John", surname: "Doe" }
console.log(userDetails); // outputs { email: "john@doe.com", displayName: "SuperCoolJohn", joined: "2016-05-05", image: "path-to-the-image", followers: 45 }
求函数的参数和
function sumArguments() { return Array.from(arguments).reduce((cur, pre) => cur + pre); } sumArguments(1, 2, 3); // => 6
map用Array.form替换,代码可能会整洁
var friends = [ {name: '小明0', age: 22}, {name: '小明1', age: 23}, {name: '小明2', age: 24}, {name: '小明3', age: 25}, ] var res = Array.from(friends, ({name})=>name) console.log(res) ["小明0", "小明1", "小明2", "小明3"]
// 拷贝数组
var numbers = [1, 2, 3]
var [...copy] = numbers
数组转对象,可用于后台传递数字情况,对应的value值
var friends = ["小明0", "小明1", "小明2", "小明3"] var friendsObj = {...friends} console.log(friendsObj)
预览图片的功能,常用有两个
URL.createObjectURL()和FileReader
URL.createObjectURL静态方法会创建一个DOMString,其中包含一个表示参数中给出的对象URL,这个URL的生命周期和创建它的窗口中的document绑定
这个心的URL对象表示指定的File对象或Blob对象。
用法 objectURL = URL.createObjectURL(object)
其中,object参数指用于创建URL的FIle对象、Blob对象或者MediaSource对象
对于input[type=file]而言, input.files[0]可以获取到当前选中文件的File对象
FileReader对象允许Web应用程序 异步读取存储在用户计算机上的文件(或原始数据缓冲区) 的内容,使用File或Blob对象指定要读取的文件或数据
原理是通过FileReader.prototype.readAsDataURL()方法把图片文件转成base64编码,然后把base64编码替换到预览图片的src属性
const $ = document.getElementById.bind(document); const $inputFile = $('inputFile'); const $previewImage = $('previewImage'); $inputFile.addEventListener('change', function () { const file = this.files[0] const reader = new FileReader() // 监听reader对象的onload事件,当图片加载完成时,把base64编码赋值给预览图片 reader.addEventListener('load', function () { $previewImage.src = reader.result }, false) // 调用reader.readerAsDataURL方法,把图片转成base64 if (file) { reader.readAsDataURL(file) } }, false)
递归获取json中的某条id值
var data = [{ id: 1, name: '家电', goods: [{ id: 11, gname: '冰箱', goods: [{ id: 111, gname: '海尔' }, { id: 112, gname: '美的' }, ] }, { id: 12, gname: '洗衣机' }] }, { id: 2, name: '服饰' }]; function getID(json, id){ var o = {} json.forEach((item)=>{ if(item.id === id){ o = item return o } else if(item.goods && item.goods.length){ o = getID(item.goods, id) } }) return o } console.log(getID(data, 112))
localStorage模拟cookie
localStorage
是长效存储的,但是有的场景希望用它来实现数据缓存功能,并且像 cookie
一样可以设置时间
/** * * 设置本地存储 * @param {string} name key * @param {*} value value 可以是string、obj等 * @param {number} time 缓存时间(ms) * */ export const setStorage = (name, data, cacheTime) => { if (!name) return const storage = {createdTime: new Date().getTime(), cacheTime, data,} window.localStorage.setItem(name, JSON.stringify(storage)) } /** * * 获取本地存储 * 如果未设置缓存时间或者在缓存时间内则返回数据 * * 如果过期则返回 undefined * @param {string} name key * */ export const getStorage = name => { if (!name) return const storage = JSON.parse(window.localStorage.getItem(name)) if (!storage) return if (storage.cacheTime && new Date().getTime() - storage.createdTime > storage.cacheTime) { clearStorage(name) return } return storage.data } /** * * 清除本地存储 * @param {string} * name key * */ export const clearStorage = name => { if (!name) return window.localStorage.removeItem(name) }
localStorage
是键值对的结构,使用起来比较方便,可以 getItem/setItem
,甚至直接 localStorage.xxx
都可以(当然最好不要这样)。
而 cookie
的存取就比较麻烦,当然业界也有封装好的方法可以使用。
因为 cookie
不允许跨域访问,为了突破这个限制,可以使用 postmessage
和 localstorage
进行数据跨域共享