Replies: 5 comments 3 replies
-
👉 forEach
💠 语法arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
|
Beta Was this translation helpful? Give feedback.
-
👉 map
💠 语法var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
✍️ 实现Array.prototype.myMap = function(callback) {
arr = [];
for (var i = 0; i < this.length; i++) {
arr[i] = callback(this[i], i, this);
}
return arr;
} 📌 测试var arr = [1, 2, 3];
var newVal = arr.myMap(i => Math.pow(i, 2));
console.log(newVal); // [1, 9, 16] 🔗 参考链接 |
Beta Was this translation helpful? Give feedback.
-
👉 sleep指定时间内函数暂停执行。 在 C 或 PHP 等编程语言中,可以调用 JavaScript 没有原生的休眠功能,但由于引入了 promises(以及 ES2018 中的 ✍️ 实现function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
} 📌 测试async function testSleep() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two seconds later, showing sleep in a loop...');
// Sleep in loop
for (let i = 0; i < 5; i++) {
if (i === 3) await sleep(2000);
console.log(i);
}
}
testSleep(); 🔗 参考链接 |
Beta Was this translation helpful? Give feedback.
-
👉 filter💠 语法var newArray = arr.filter(callback(element[, index[, array]])[, thisArg]) ✍️ 实现Array.prototype.myFilter = function(callback, context) {
var arr = [];
var idx = 0;
for (var i = 0; i < this.length; i++) {
if (callback.call(context, this[i], i, this)) {
arr[idx++] = this[i];
}
}
return arr;
} 📌 测试var arr = [1, 2, 3, 4, 5];
var newVal = arr.myFilter(i => i > 3);
console.log(newVal); // [4, 5] 🔗 参考链接 |
Beta Was this translation helpful? Give feedback.
-
👉 curry在计算机科学中,柯里化(英语:Currying),又译为卡瑞化或加里化,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术。这个技术由克里斯托弗·斯特雷奇以逻辑学家哈斯凯尔·加里命名的,尽管它是 Moses Schönfinkel 和戈特洛布·弗雷格发明的。
✍️ 实现function curry(func) {
return function curried(...args) {
// 如果参数的数量(args.length)大于或等于原函数中定义的参数数量(func.length),
// 则直接使用 func.apply 将参数传递。
if (args.length >= func.length) {
return func.apply(this, args);
}
// 否则,我们只得到一部分参数,此时还未调用 func,
// 则返回一个新的匿名函数,重新柯里化,提供之前的参数(args)和当前匿名函数参数(args2)。
return function(...args2) {
return curried.apply(this, args.concat(args2));
};
};
} 📌 测试function sum(a, b, c) {
return a + b + c;
}
const currySum = curry(sum);
currySum(1, 2, 3); // 6 - 未柯里
currySum(1)(2)(3); // 6 - 完全柯里
currySum(1)(2, 3); // 6 - 第一个参数柯里 🔗 参考链接 |
Beta Was this translation helpful? Give feedback.
-
查看源码 js-wheel
Standard
Array
Function
Utils
Beta Was this translation helpful? Give feedback.
All reactions