简体   繁体   English

如何在 JS ES6 中的数组内向数组中添加元素?

[英]How to add an element to an array inside an array in JS ES6?

For example, I know I can use spread operator to add an element to an array in ES6.例如,我知道我可以使用扩展运算符在 ES6 中将元素添加到数组中。

const arr = ["a","b"]
const newArr = [...arr, "c"]

that I get我得到

["a","b","c"]

But how to implement this in an nested array, like但是如何在嵌套数组中实现这一点,比如

const arr = [["a","b"], ["d"]]

I want to get我想得到

newArr1 = [["a","b","c"], ["d"]]

and

newArr2 = [["a","b"],["d","c"]]

Perhaps we can use也许我们可以使用

[[...arr[0], 'c'], [...arr[1]]]

but what if但如果

const arr = [["a","b"], ["d"],["e"]]

and I still want我仍然想要

[["a","b","c"], ["d"],["e"]]
is there a common way?

You can simply use the array index or use findIndex and find methods, in case you want to remove not based on the index您可以简单地使用数组索引或使用 findIndex 和 find 方法,以防您不基于索引删除

const arr = [[a,b], [d]]
arr[1].push(c)
//arr = [[a,b], [c,d]]
const array = [['a', 'b'], ['d']]
const arrayIndex = array.findIndex(item => item.find(i => i === 'd'))
if (arrayIndex !== -1) {
  const oldArray = array.find(item => item.find(i => i === 'd'))
  const newArray = [...oldArray, 'c']
  array[arrayIndex] = newArray
}
console.log(array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM