1、对象数组去重:

数组去重:

    const a=[{a:1,b:2},{a:2},{a:2},{a:1,c:3},{b:2,a:1}]

结果:[{a:1,b:2},{a:2},{a:1,c:3}]

// 判断两个对象属性是否一致
const a = [{ a: 1, b: 2 }, { a: 2 }, { a: 2 }, { a: 1, c: 3 }, { b: 2, a: 1 }]
const isSameObject = (a, b) => {
    if (Object.keys(a).length !== Object.keys(b).length) return false;
    for (const key in a) {
        if (Object.hasOwnProperty.call(a, key)) {
            if (a[key] !== b[key]) return false
        }
    }
    return true;
}
const uniqueFn = (tempArr) => {
    const res = tempArr.slice(0)
    for (let i = 0; i < tempArr.length; i++) {
        for (let j = i + 1; j < tempArr.length; j++) {
            if (isSameObject(tempArr[i], tempArr[j])) {
                console.log(i, j);
                res.splice(i, 1)
            };
        };
    };
    return res;
}
console.log(uniqueFn(a));

2、事件循环相关 

setTimeout(function() {
    console.log('setTimeout1');    // 8  setTimeout1
    new Promise(function(resolve) {
        console.log('promise0');  // 9  promise0
        resolve()
    }).then(function() {
        console.log('settimeout promise resolveed');   // 10  settimeout promise resolveed
    })
});

setTimeout(function() {
    console.log('setTimeout2');  // 11  setTimeout2
});

const P = new Promise(function(resolve) {
    console.log('promise');    // 1  promise
    for (var i = 0; i < 10000; i++) {
        if(i === 10) {
            console.log('for'); // 2  for
        }
        if (i === 9999) {
            resolve('resolve'); 
        }
    }
}).then(function(val) {
    console.log('resolve1');    // 5  resolve1
}).then(function(val) {
    console.log('resolve2');     // 6  resolve2
});

new Promise(function(resolve) {
    console.log('promise2');     // 3  promise2
    resolve('resolve');
}).then(function(val) {
    console.log('resolve3');   //  7  resolve3
})
console.log('console');       // 4  console

3、扁平化数组

实现一个flat函数,把嵌套的数组打平,flat([[1,2,[3,[4,[5]]]]]),返回[1,2,3,4,5]

const flat = (nums) => {
    const res = nums.reduce((pre, cur) => {
        if (Array.isArray(cur)) {
            return [...pre, ...flat(cur)]
        } else {
            pre.push(cur)
        }
        return pre
    }, [])
    return res;
}
console.log(flat([[1, 2, [3, [4, [5]]]]])); // [ 1, 2, 3, 4, 5 ]

原文地址:https://blog.csdn.net/ggbee_/article/details/134750262

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_34584.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注