1、map的实现
Array. = function (callback) { const len = ; const res = []; if (len > 0) { for (let i = 0; i < len; i++) { res.push(callback(this[i], i)); } } return res; }; const arr = [ { a: 1, b: 2, c: 3, d: 4 }, { a: 5, b: 6, c: 7, d: 8 }, { a: 9, b: 10, c: 11, d: 12 }, ]; const mapRes = arr.myMap((item, index) => i); con(mapRes); // [4, 8, 12]
2、some的实现
Array. = function (callback) { const len = ; const res = false; if (len > 0) { for (let i = 0; i < len; i++) { let res = callback(this[i], i); if (res === true) return true; } } return res; }; const arr1 = [1, 2, 3, 4]; const someRes1 = arr1.mySome((item) => item < 2); const someRes2 = arr1.mySome((item) => item > 4); con(someRes1, someRes2); // true false
3、every的实现
Array. = function (callback) { const len = ; let res = 0; if (len > 0) { for (let i = 0; i < len; i++) { if (callback(this[i], i) === true) { res++; } } } con(res, len); return res === len; }; const arr1 = [1, 2, 3, 4]; const everyRes1 = arr1.myEvery((item) => item < 4); const everyRes2 = arr1.myEvery((item) => item > 0); con(everyRes1, everyRes2); // false true