簡體   English   中英

使用array.map()更改數組索引

[英]Change array index with array.map()

是否有可能使用Array.map()在JS中迭代數組並修改所得數組的索引值?

// 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"},
];
*/

Array#map可以執行1:1映射(可以這么說)。

您必須創建一個新數組,並將元素顯式分配給特定索引:

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

當然,您也可以使用.reduce

當然,您可以按照以下步驟進行操作;

 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)); 

這並不奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM