使用array.map()更改数组索引

时间:2016-08-16 19:16:35

标签: javascript arrays

是否有可能使用Array.map()在JS中迭代数组并修改结果数组的 index 值?

// I start with this values:
var arrSource = [
  {id:7, name:"item 1"}, 
  {id:10, name:"item 2"},
  {id:19, name:"item 3"},
];

var arrResult = arrSource.map(function(obj, index) {
    // What to do here?
    return ???; 
});

/*
This is what I want to get as result of the .map() call:

arrResult == [
  7: {id:7, name:"item 1"}, 
  10: {id:10, name:"item 2"},
  19: {id:19, name:"item 3"},
];
*/

2 个答案:

答案 0 :(得分:3)

没有。 Array#map执行1:1映射(可以这么说)。

您必须创建一个新数组并明确地将这些元素分配给特定索引:

var arrResult = [];
arrSource.forEach(function(value) {
   arrResult[value.id] = value;
});

当然,您也可以使用.reduce

答案 1 :(得分:0)

当然你可以这样做;



var arrSource = [
  {id:7, name:"item 1"}, 
  {id:10, name:"item 2"},
  {id:19, name:"item 3"},
];

newArr = arrSource.map((e,i,a) => a[a.length-1-i]);
console.log(newArr)




是的...如果您需要Array.prototype.map()的某些违规行为,例如

,则源数组始终会发生变异



var arrSource = [
  {id:7, name:"item 1"}, 
  {id:10, name:"item 2"},
  {id:19, name:"item 3"},
];

newArr = arrSource.map((e,i,a) => a[a.length] = e);
console.log(JSON.stringify(arrSource,null,4));




这并不奇怪。