【问题标题】:In Javascript how do I create a secondary array in a specific index?在 Javascript 中,如何在特定索引中创建辅助数组?
【发布时间】:2022-01-22 11:15:45
【问题描述】:

如何在 Javascript 中从现有数组创建子数组?

例如;

Arr = [5,2,1,2]

然后我想在Arr的位置1插入8,但保持原值2。所以arr可以变成:

Arr = [5,[2,8],1,2]

我尝试使用 concat,它做了一些事情但会复制所有值。

请记住,这可能会增长,例如Arr = [5,[2,8,3,4],1,[2,3]]

谢谢!

【问题讨论】:

  • 你的意思是你只想要唯一的值吗?

标签: javascript arrays data-manipulation


【解决方案1】:

您可以分配连接的值。

const
    addAt = (array, value, index) => array[index] = [].concat(array[index], value),
    array = [5, 2, 1, 2];

addAt(array, 8, 1);
console.log(array)

addAt(array, 3, 1);
console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    有几种不同的方法可以做到这一点,但您可以像这样将当前数组索引重新分配给数组:

    Arr[1] = [Arr[1], 8]。然后,如果您想继续添加到 Arr 中索引 1 处的数组,您可以执行 Arr[1].push(x) 之类的操作。

    【讨论】:

    • 谢谢@mars!!!
    【解决方案3】:

    您可以这样做(可能不是最佳答案,但可能会有所帮助)

    const addIntoArray = (arr, toAdd, index) => {
      arr[index] = typeof arr[index] == "number" ? [arr[index], toAdd] : [...arr[index], toAdd];
      return arr
    }
    
    Arr = [5,2,1,2]
    
    console.log(Arr); // [ 5, 2, 1, 2 ]
    addIntoArray(Arr, 1, 1)
    console.log(Arr); // [ 5, [ 2, 1 ], 1, 2 ]
    addIntoArray(Arr, 3, 1)
    console.log(Arr) // [ 5, [ 2, 1, 3 ], 1, 2 ]
    

    基本上...arr 扩展数组,然后我们在其末尾添加toAdd[arr[index], toAdd] 创建一个数组,其中第一个元素作为数字,第二个元素作为新元素。 (它修改了原始数组,如示例所示,请注意,可能会导致错误)

    typeof arr[index] == "number" 只是一个简单/通用的类型检查,以查看是否还没有数组

    【讨论】:

    • 谢谢亚历山大!这也很好用!
    【解决方案4】:

    这个功能应该满足你的基本条件

    // a - array, v - value to insert, i - position to insert 
    const avi = (a, v, i) => { 
      r = a.slice(0, i); 
      r.push([a[i], v]);
      a.slice(i+1, a.length).forEach(e => r.push(e)); 
      return r;
    }
    
    console.log(JSON.stringify(avi([5,2,1,2], 8, 1)))
    //=> "[5,[2,8],1,2]"
    

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2023-03-30
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多