JavaScript keluar dari peta
// You cannot break out of `Array.protoype.map`.
/*
Map is essentially a for loop that applies a
function to each value of an array and pushes it
to a new array.
*/
// A simple recreation of `Array.prototype.map`:
Array.prototype.map = function(callbackfn) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callbackfn(result, i, this));
}
return result;
};
/*
Essentially, you can just create a new array and
use a for loop which you can break from:
*/
const arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const arrX2 = [];
for (let i = 0; i < arr.length; i++) {
if (i >= 5) {
break;
}
arrX2.push(arr[i] * 2);
}
/*
Although if you are 100% set on 'breaking' from
`Array.prototype.map`, you could customise the
function to suit you. Have a look at this example:
*/
Array.prototype.map = function(callbackfn) {
const result = [];
let _break = false;
function breakFunc() { _break = true; }
for (let i = 0; i < this.length; i++) {
/*
we need to store the item so we don't
automatically push undefined to the
array if the break function is
called.
*/
const item = callbackfn(this[i], i, this, breakFunc);
if (_break) {
return result;
}
result.push(item);
}
return result;
};
const arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const arrX2 = arr.map((item, index, array, fakeBreak) => index >= 5 ? fakeBreak() : item);
/*
You could create your own custom `Array.prototype.map`
like the one above if you really wanted, but it is
probably better to just use a normal for loop.
*/
MattDESTROYER