简体   繁体   English

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

[英]How to splice an array out of a nested array - javascript

I am attempting to splice a nested array out of its parent array. 我试图从其父数组中拼接出一个嵌套数组。 Consider the following array. 考虑以下数组。 items.splice(0,1) should give me the first nested array([1,2]), however it seems to give me the first nested array, still nested inside of an array: items.splice(0,1)应该给我第一个嵌套数组([1,2]),但是它似乎给了我第一个嵌套数组, 仍然嵌套在数组内部:

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]]

However it seems to return the needed array (first item), in another array. 但是,它似乎在另一个数组中返回了所需的数组(第一项)。 And I'm not able to get the full array unless I do item[0] . 除非我执行item[0]否则我无法获得完整的数组。 What in the world am I missing!? 我到底在想什么!

The MDN says Array.prototype.splice : 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. 如果没有删除任何元素,则返回一个空数组。

So, it won't return just the deleted element, it will be wrapped in an array. 因此,它不会仅返回已删除的元素,而是将其包装在数组中。

splice() changes the contents of an array, and returns an array with the deleted elements. splice()更改数组的内容,并返回包含已删除元素的数组。

In your case, your original array has elements that also happen to be arrays. 在您的情况下,原始数组的元素也恰好是数组。 That might be confusing you. 这可能会使您感到困惑。

.splice() is returning correct array at item ; .splice()返回item正确数组; try selecting index 0 of returned array to return [1,2] ; 尝试选择返回数组的索引0以返回[1,2] to "flatten" item , try utilizing Array.prototype.concat() ; 要“拼合” item ,请尝试利用Array.prototype.concat() ; see How to flatten array in jQuery? 请参阅如何在jQuery中展平数组?

 var items = [[1,2],[3,4],[5,6]]; var item = items.splice(0,1); // should slice first array out of items array // https://stackoverflow.com/a/7875193/ var arr = [].concat.apply([], item); console.log(item[0], arr); 

You should reference the first array in items, and then splice it. 您应该在项目中引用第一个数组,然后对其进行拼接。 Try working snippet below. 尝试使用下面的代码段。

 var items = [[1,2],[3,4],[5,6]]; var item = items[0].splice(0,2); console.log(item); 

To replace a two dimensional array you should use array[row][col] for example 要替换二维数组,您应使用array [row] [col]例如

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);

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

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