输入n个数组,返回交集
let a = [2, 3];
let b = [2, 3, 5];
let c = [2, 3, 5, 6, 7];
function intersect(...args) {
if (args.length === 0) {
return [];
}
if (args.length === 1) {
return args[0];
}
return args.reduce((prev, next) => {
return prev.filter((i) => next.indexOf(i) > -1);
});
}
仿Object.assign的功能
let obj1 = { a: 1, b: { a: 1 }, c: 3, };
let obj2 = { a: 1, b: { a: 'i' }, e: 3, };
function assign(to, from) {
if (to === from) {
return to;
}
from = Object(from);
Object.keys(from).forEach((item, index) => {
to[item] = from[item]
});
return to;
}
console.log(assign(obj1, obj2));
仿Array.map的功能
rray.prototype.myMap = function (fn, context) {
let resArr = [];
const me = this;
const ctx = context ? context : me;
if (typeof fn !== "function") {
throw new Error(`${fn} is not a function`);
}
me.forEach((item, index) => {
resArr.push(fn.call(ctx, item, index, me));
});
return resArr;
};
const arr = [1, 2, 3];
const ar1 = [3, 9, 8];
const newArr = arr.myMap(function (item, index, _arr) {
return item * 2;
}, ar1);