如何从嵌套数组拼接数组 - javascript

How to splice an array out of a nested array - javascript

我正在尝试从其父数组拼接一个嵌套数组。考虑以下数组。 items.splice(0,1) 应该给我第一个嵌套数组 ([1,2]),但是它似乎给了我第一个嵌套数组,still 嵌套在一个数组中:

var items = [[1,2],[3,4],[5,6]];

var item = items.splice(0,1); // should slice first array out of items array

console.log(item); //should log [1,2], instead logs [[1,2]]

不过似乎return需要的数组(第一项)在另一个数组中。除非我 item[0],否则我无法获得完整的数组。我到底错过了什么!?

splice() 更改数组的内容,returns 更改包含已删除元素的数组。

在您的情况下,您的原始数组中的元素也恰好是数组。这可能会让您感到困惑。

MDN 说 Array.prototype.splice:

Returns

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

所以,它不会return只是被删除的元素,它会被包裹在一个数组中。

.splice() 是 return 在 item 处的正确数组;尝试选择 returned 数组的索引 0 到 return [1,2] ;到 "flatten" item ,尝试使用 Array.prototype.concat() ;见 How to flatten array in jQuery?

var items = [[1,2],[3,4],[5,6]];

var item = items.splice(0,1); // should slice first array out of items array
// 
var arr = [].concat.apply([], item);

console.log(item[0], arr);

要替换二维数组,您应该使用数组[行][列],例如

for(var row = 0; row < numbers.length; row++) {
    for(var col = 0; col < numbers[row].length; col++) {
        if (numbers[row][col] % 2 === 0) {
            numbers[row][col] = "even";
        } else {
            numbers[row][col] = "odd";
        }  
    }

}
console.log(numbers);

应该引用items中的第一个数组,然后拼接。试试下面的工作代码段。

var items = [[1,2],[3,4],[5,6]];

var item = items[0].splice(0,2);

console.log(item);