Array.from 达到map的效果
let arr=[
{name:'小智1',age:23},
{name:'小智2',age:13},
{name:'小智3',age:43},
{name:'小智4',age:33},
];
console.log(Array.from(arr, ({name}) => name));
// [ '小智1', '小智2', '小智3', '小智4' ]
console.log(arr.map(val => val.name));
// [ '小智1', '小智2', '小智3', '小智4' ]
将数组转换为对象
let arr = ['小智1', '小智2', '小智3', '小智4'];
let obj={...arr};
console.log(obj);
// { '0': '小智1', '1': '小智2', '2': '小智3', '3': '小智4' }
是否有这个属性
const hasKey = (obj, key) => {
if (key.includes('.')) {
let _key = key.split('.')[0];
if (typeof obj[_key] === 'object')
return hasKey(obj[_key], key.slice(key.indexOf('.') + 1))
}
return Object.keys(obj).includes(key);
}
let obj = {
a: 1, b: { c: 4 }, 'd.e': 5
}
hasKey(obj, 'a'); // true
hasKey(obj, 'b'); // true
hasKey(obj, 'b.c'); // true
hasKey(obj, 'd.e'); // true
hasKey(obj, 'd'); // false
hasKey(obj, 'f'); // false
// 优化
const hasKey = (obj, keys) => {
return (keys.length > 0) && keys.every(key => {
//当没有这个属性
if (typeof obj !== 'object' || !Reflect.ownKeys(obj,key)) {
return false
}
obj = obj[key];
return true
})
};
let obj = {
a: 1,
b: { c: 4 },
'b.d': 5,
};
console.log(hasKey(obj, ['b','c']));
console.log(hasKey(obj, ['b.d']));
对象转成网址的那种
const objectToQueryString = query => {
if (query) {
return Object.entries(query).reduce((acc, [key, val], index) => {
const symbols = index === 0 ? '?' : '&';
acc += typeof val === 'string' ? `${symbols}${key}=${val}` : '';
return acc
}, '')
} else {
return ''
}
};
console.log(objectToQueryString({page: '1', size: '2ky', key: undefined}));
// ?page=1&size=2ky
判断偶数(从0开始)
const odd=num=>num%2===1;
console.log(odd(5));
获取当前时间
const currentTime = () => {
let t = new Date();
t.setHours(t.getHours() + 8);
let arr = t.toISOString().split(/[T.]/);
return arr[0]+' '+arr[1]
};
去重
let arr = [
{age: 1, name: '张三'},
{age: 1, name: '张三'},
{age: 2, name: '李四'},
{age: 3, name: '张三'},];
let arr1 = arr.map(val => val.name);
console.log(arr.filter((val, index) => arr1.indexOf(val.name) === index));
// [ { age: 1, name: '张三' }, { age: 2, name: '李四' } ]
判断两个数组的每一项是否相等
// a是小的,b是大的
const arrayEqual = (a, b) => {
if (!(Array.isArray(a) && Array.isArray(b))) {
return false
}
if (a.length !== b.length||a.length > b.length) {
return false;
}
return a.reduce((acc, val, index) => val === b[index])
};
console.log(arrayEqual([1, 2, 3], [1, 2, 3])); //true
22|0Generator 函数遍历数组
Generator 函数遍历数组
let arr = [
{name: 'zs',age: 38,gender: 'male'},
{name: 'yw',age: 48,gender: 'male'},
{name: 'lc',age: 28,gender: 'male'},
];
function* loop(arr) {
for(let item of arr){
yield item;
}
}
let repoGen = loop(arr);
console.log(repoGen.next());
// { value: { name: 'zs', age: 38, gender: 'male' }, done: false }
console.log(repoGen.next());
// { value: { name: 'yw', age: 48, gender: 'male' }, done: false }
数组去重
function arr1(){
var n=[];
for(var i=0;i<arr.length;i++){
if(n.indexOf(arr[i])==-1){
n.push(arr[i])
}
}
return n;
}
再次提一些异步
const getUser = () => new Promise((resolve, reject) => {
resolve('zhangsan');
reject('失败')
}).then(resolver=>{
console.log(resolver)
})
async function add() {
console.log(1)
await getUser()
console.log(3)
}
add()
/*
* 1
zhangsan
3
* */
彻底弄懂怎么正确使用async/await
//微任务
const p1 = () => new Promise((resolve, reject) => {
resolve('微任务')
}).then(res => {
console.log(res)
})
//宏任务
const p2 = () => new Promise(res => setTimeout(() => {
res('宏任务')
},1000)).then(res => {
console.log(res)
})
const add = async () => {
console.log(1)
await p2()
await p1()
console.log(4)
}
add()
简化成函数
const pipeAsync = (...args) => arg => args.reduce((acc, val) => {
return acc.then(val)
}, Promise.resolve(arg))
const sum = pipeAsync(
x => x + 1,
x => new Promise(resolve => setTimeout(() => {
resolve(x * 4)
}, 1000)),
x => new Promise(res => res(x * 10)),
x=>x+10
);
(
async () => {
//5+1 *4 *10 +10
console.log(await sum(5))
}
)()
const arrayFromRange = function arrayFromRange(min, max) {
const output = []
for (let i = min; i <= max; i++)
output.push(i)
return output
}
console.log(arrayFromRange(1, 10))
//[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
//优化后
const arrayFrom = (min, max) =>
Array.from({length: max - min+1}, (_, i) => i + min)
console.log(arrayFrom(1, 10))
//[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
网友评论