我有一个列表,其中根据颜色包含一个团队:
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,这给我的输出如下:
["绿色","蓝色","黄色","黑色","白色","红色","橙色"]
0 索引定位到 5。
现在我有一个字典,根据索引包含球队的队长。
var captians = [{'index': 0, 'captain': 'Jack'}, {'index': 1, 'captain': 'Daniel'}]
这里的0
是team
的索引。
red
队的队长是 Jack
当索引中的团队发生变化时,我想相应地更改队长。
我该怎么做??
最佳答案
您可以遍历并将区间中的所有索引移动到一个位置。
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);
关于Javascript 根据列表索引更新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37652281/