-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
手写Array.prototype.* #225
Labels
Comments
手写filter
实现const filter = (arr, callback) => {
const result = [];
for (let i = 0; i < arr.length; i++) {
const validate = callback(arr[i], i, arr);
if (validate) {
result.push(arr[i]);
}
}
return result;
}; 测试const arr = [1, 2, 3, 4];
/**
* 1.测试callback入参
*/
filter(arr, (item, index, arr) => console.log(item, index, arr));
/**
* 2.测试callback断言
*/
let filterArr = filter(arr, (item) => item > 1);
console.log(filterArr); |
手写map
实现const map = (arr, callback) => {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(callback(arr[i], i, arr));
}
return result;
}; 测试const arr = [1, 2, 3, 4];
/**
* 1.测试callback入参
*/
map(arr, (item, index, arr) => console.log(item, index, arr));
/**
* 2.测试callback映射
*/
let mapArr = map(arr, (item, index) => ({ value: item, index }));
console.log(mapArr); |
手写every
实现const every = (arr, callback) => {
let result = true;
for (let i = 0; i < arr.length; i++) {
if (!callback(arr[i], i, arr)) {
result = false;
break;
}
}
return result;
}; 测试const arr = [1, 2, 3, 4];
/**
* 1.测试callback入参
*/
every(arr, (item, index, arr) => console.log(item, index, arr));
/**
* 2.测试callback断言
*/
let everyTruthy = every(arr, (item) => item > 0);
let everyFalsy = every(arr, (item) => item > 2);
console.log(everyTruthy, everyFalsy); // true, false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
主要手写一些常用的Array.prototype上的函数。
The text was updated successfully, but these errors were encountered: