Javascript 根据列表索引更新字典

标签 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,这给我的输出如下:

["绿色","蓝色","黄色","黑色","白色","红色","橙色"]

0 索引定位到 5。

现在我有一个字典,根据索引包含球队的队长。

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

这里的0team的索引。 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/

相关文章:

javascript - 单击以获取附加的 html

javascript - jQuery 事件 currentTarget 数据集

javascript - 将函数附加到左键单击 <listbox> 项目

java - 具有自身数组的对象

java - 数组中没有重复项

javascript - 带星号的正则表达式方括号

javascript - Redux:在 2D 数组上使用 Spread 运算符

java - 线程中的异常 "AWT-EventQueue-0"java.lang.ArrayIndexOutOfBoundsException : 10 for Inventory

javascript - 如何在 php 中制作二维键数组?

php - 使用 array_filter 或 array_walk 从数组中删除项目