Javascript根据列表索引更新字典

时间:2016-06-06 07:59:49

标签: javascript arrays

我有一个列表,其中包含一个根据颜色的团队:

var team = ["Red","Green","Blue","Yellow","Black","White","Orange"]
var from = 0
var to = 5
team.splice(to, 0, team.splice(from, 1)[0])
console.log(team)

在这里,我正在将团队的索引从0改为5,这给我的输出如下:

["Green","Blue","Yellow","Black","White","Red","Orange"]

0指数定位为5。

现在我有一本字典,其中包含根据索引的团队队长。

var captians = [{'index': 0, 'captain': 'Jack'}, {'index': 1, 'captain': 'Daniel'}]

此处0team的索引。 团队red的队长是Jack 当团队在索引中改变时,我想相应地改变队长。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以迭代并移动区间中的所有索引。



var team = ["Red", "Green", "Blue", "Yellow", "Black", "White", "Orange"],
    from = 0,
    to = 5,
    captians = [{ 'index': 0, 'captain': 'Jack' }, { 'index': 1, 'captain': 'Daniel' }];

team.splice(to, 0, team.splice(from, 1)[0]);

captians.forEach(function (a) {
    if (a.index === from) {
        a.index = to;
        return;
    }
    if (from < to && a.index > from && a.index <= to) {
        a.index--;
    }
    if (from > to && a.index >= to && a.index < from) {
        a.index++;
    }
});

console.log(captians);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

captians.map((item)=>
{
   if(item['index'] == to){
        item['index'] = from
   }else if(item['index'] == from){
        item['index'] = to
   }else{
        if(item['index']> from && item['index']<to){
               item['index'] -=1;
        }
   }
})

答案 2 :(得分:0)

你需要对象而不是数组。以下更改在这种情况下效果最佳:

&#13;
&#13;
var team = {0:'Red',1:'Green',2:'Blue',3:'Yellow',4:'Black',5:'White',6:'Orange'};

var captains = {0 : 'Jack', 1: 'Daniel', 2: 'Mark',3:'Joan',4:'Sarah',5:'Mindy',6:'Stuart',7:'Jane'};

function swapTeam(from, to){
temp = team [to];
team[to] = team[from];
team[from] = temp;

temp = captains[to];
captains[to] = captains[from];
captains[from] = temp;
}





swapTeam(0,5);
console.log(team);
console.log(captains);
&#13;
&#13;
&#13;