如何将 map 函数获取到 return 大于第一个数组的数组?

How can I get the map function to return an array which is greater than the first?

来自 Array.prototype.map doucmentation,它提到应该可以从 map 回调中改变调用 map 的数组,它采用三个参数,#1 值,#2 索引, #3 原数组,除以下内容:

thisArgOptional Value to use as this when executing callback. ... Parameters in Detail

callback is invoked with three arguments: the value of the element, the index of the element, and the array object being mapped.

If a thisArg parameter is provided, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

map does not mutate the array on which it is called (although callback, if invoked, may do so).

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback.

所以好像是说虽然值"added to the original array"不会被map遍历,但这意味着确实可以从map内部追加到原始数组。但是,我不确定该怎么做,因为简单地使用第三个数组参数并附加到它似乎什么都不做(如果我将它存储到一个数组中,我不能只使用原始数组变量名,因为映射 returns 一个全新的数组):

var myArr = [
  1, 2, 3, 4, 5
].map(function(x, i, arr) {
    this.push(i); //references old array so does nothing
    arr.push(i); //seemingly it should adjust
    return x;
}, myArr /*
  attempting to use "this"
  arg to see if it will work,
  although seemingly its not recognized
*/
);

console.log(myArr); //only returns original value

更新

为了回答您的评论,.map() 不是将值附加到数组的正确工具。当您需要修改输入数组的每个元素时,您应该使用它,例如将每个值加倍:

var input = [1,2,3,4,5];
var myArr = input.map(function (x) {
  return x * 2;
});

myArr.push(6,7); // Append your values in a separate statement.

console.log(myArr); // [2,4,6,8,10,6,7]

然后根据您想要实现的目标,在地图之前或之后的单独步骤中附加新值。

说明

您的代码未按您预期的方式运行。 console.log(myArr) 看起来像是在打印原始数组,但实际上不是。例如,如果您删除所有其他代码,您将剩下:

var myArr = [1,2,3,4,5].map(function (x) {
  return x;
});

console.log(myArr); // [1,2,3,4,5]

您可以看到我们只是 returning x 没有做任何更改。 x 将解析为 1,然后 2,依次类推。因此,.map() 的输出将是 [1,2,3,4,5],它包含与您的输入数组相同的值,但不是完全相同的数组,它是一个副本。

您可以通过将输入数组移动到一个新变量中然后在末尾比较 myArr === input 来证明这一点:

var input = [1,2,3,4,5];
var myArr = input.map(function (x) {
  return x;
});

console.log(input); // [1,2,3,4,5]
console.log(myArr); // [1,2,3,4,5]
console.log(myArr === input); // false

为了更进一步,如果我们采用 .map() 的第三个参数并将每个元素替换为其值的两倍,我们将看到原始 input 数组 是否被修改,.map()myArr 的 return 值保持不变。

var input = [1,2,3,4,5];
var myArr = input.map(function (x, i, arr) {
  arr[i] = x * 2;
  return x;
});

console.log(input); // [2,4,6,8,10]
console.log(myArr); // [1,2,3,4,5]
console.log(myArr === input); // false

奖励积分

仅仅因为您可以使用.map()的第三个参数修改原始数组并不意味着您应该这样做。这样做可能会引入意外行为,并使未来的开发人员更难推断代码在做什么。

你的函数 return 一个新变量比改变输入参数要好得多。