简体   繁体   中英

Adding to a 2 dimensional array with unshift

I have a 2 dimensional array:

var sH = [['two'],['three']]

and I want to add 'one' to the start/top so my array ends up as

 [['one'],['two'],['three']]

Using unshift like so

sH[0].unshift('one');

produces an array where 'one is inserted but 'two' is in the second column rather than the first (ie 1 rather than 1 [0]) I've looked and searched and experimented but I cannot see how to do this easily.

The statement sH[0].unshift will affect the bound object - which is an array ( the first of the existing two (two, three); which is two)

In other words, using that method you adds the "one" to the first existing child array which is "two", producing [['one', 'two'], 'three']

To produce [['one'], ['two'], ['three']] you should use sH.unshift('one');

也许我误会了,但是您不是只想执行以下操作吗?

sH.unshift(['one'])
var sH = [['two'],['three']];
sH.unshift(['one']); // [["one"], ["two"], ["three"]]
sH.push(['four']); // [["one"], ["two"], ["three"], ["four"]]

You are doing it wrong with your sh index.

It should be sh.unshift(['one']);

This will insert an array containing "one" string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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