簡體   English   中英

刪除數組數組的第一項

[英]Remove first item of array of array

如何從數組下面的數組中刪除 1 和 3?

[[1,2], [3,4,5]]

[[2],[4,5]]

正在考慮 pop() 但卡在某個地方。

嘗試使用 JavaScript 內置 function shift()

var a = [[1,2], [3,4,5]];

a.map(item => { 
    item.shift();
    return item;
});

console.log(a); // [[2], [4, 5]]

官方指南: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

您可以使用map拼接

const a = [[1,2], [3,4,5]];

console.log(
  a.map(item => item.splice(1))
)

基本上,您將數組的每個項目映射到沒有第一個元素的相同數組(因為splice改變了數組)。

如果您還想要內部數組的副本,那么您應該使用slice代替。

像往常一樣循環遍歷主數組,例如

    let array = [[1,2], [3,4,5]]
    for (let el of array) {
         // Now you'll be accessing each array inside the main array,
         // YOu can now remove the first element using .shift()
         el.shift();
     }

您可以 map 陣列,並得到所有項目,但第一個,與Array.slice()

 const arr = [[1,2], [3,4,5]]; const result = arr.map(item => item.slice(1)); console.log(result);

嘗試這個:

 var arr = [[1,2], [3,4,5]]; for (var innerArray of arr) { // Using array.splice() for (var element of innerArray) { if (element === 1 || element === 3) innerArray.splice(innerArray.indexOf(element), 1); } } console.log(arr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM