Javascript multidimensional array updating specific element

I have a string that has been converted to a 2D array in js.

board = "... | .X. | ... |"

Used to represent the playing field

every. represents space

each | represents a string

each X represents a wall

EDIT: code below to create a 2d array

var src= "...|.X.|...|";
board = src.split(/\|/g);

for (var i = 0; i < board.length; i++) {
var cells = board[i].split('');
for (var j = 0; j < cells.length; j++) {
    cells[j] = parseInt(cells[j]);
}
board[i][j] = cells;
console.log(board[1][1])
//returns 'X'

      

when i access board [i] [j] it returns correctly:

[0] [0] = "."

[1] [1] = "X"

[1] [2] = "."

etc.

I want to update a specific element with a string representing a chunk. However, when I insert into an element like this:

board [0] [0] = "piece4"

The array is returned to firebug like this:

board = "piece4 | .X. | ... |"

When will it look like:

board = ".piece4. | .X. | ... |"

Why are items [0] [1] and [0] [2] being overwritten? Am I not understanding array access arrays correctly in js?

+3


source to share


4 answers


Problem:

I'm pretty sure you have a one-dimensional array with strings stored in each one. So your array looks like this:

array (
    [0] => '...',
    [1] => '.X.',
    [2] => '...'
)

      

If this is what you want:

array (
    [0] => array (
        [0] => '.',
        [1] => '.',
        [2] => '.'
    ),
    [1] => array (
        [0] => '.',
        [1] => 'X',
        [2] => '.'
    ),
    [2] => array (
        [0] => '.',
        [1] => '.',
        [2] => '.'
    )
)

      




DECISION:

When constructing your 2D array, make sure you explicitly declare each entry in board

an array. So to create it, your code might look something like this:

board = new Array();
rows = 3;
for (var i = 0; i < rows; i++)
    board[i] = new Array('.', '.', '.');

      

+3


source


I had the same problem, but I had a more complex reason, and I want to add it in case someone finds this page to search for the same problem as mine:

I created and populated a 2-dimensional array like this:

var foo = Array(n).fill(Array(n).fill(0));

      

which creates an n * n two-dimensional array filled with zeros.

Now when I tried to overwrite a cell like this

foo[1][1] = 1;

      



I got these values:

[[0,1,0],
 [0,1,0],
 [0,1,0]]

      

which is really amazing IMHO.

The reason for this was that there was only one line that was referenced three times three times. So when I changed the first index on the second line, it effectively changed all lines.

Bottom line: don't use Array.fill

to create multidimensional arrays!

+10


source


Two notes here:

  • Arrays start at index 0 in each dimension.
  • If you are treating a string as a 2D array, each element is a char, not a string.

So, if you write board[0][0] = 'X';

, then you get the correct behavior (and that will change the first character of the line, not the second).

0


source


The situation and solution above is pretty straightforward. The question of updating specific values ​​in a list of objects (often called an array, but that's a discussion at other times) has more practical and industrial applications. The problem you are having is that it looks at the value in a specific cell for example. my_array [0] [0] returns "some value", will also allow you to change this value through assignment, for example. my_array [0] [0] = 'new value'. You will find that depending on how you defined your array, the change appears on the same row column by column, not what you need. See the sample code to illustrate how to create and manage a multidimensional list of objects (array).

<html>
<head>
<title>JavaScript Object List/Array</title>
<script>
//Make a JavaScript array that can manage data of inventory between different locations over time.
var list_of_brands = ["BMW","Harley Davidson","Honda","Kawasaki"];
var list_of_locations = ["Dayton","Cincinnati"];

//a month of data
var DAYS_IN_A_MONTH = 30;
var calendar = [];
for(day_of_sales = 1; day_of_sales <= DAYS_IN_A_MONTH; day_of_sales++){

  //hold your locations
  var shop_location = [];//You need to create a new array for each day - that part of the trick!

  for(location_index = 0;location_index < list_of_locations.length;location_index++){

  //set up some starting inventory
  var inventory = [];//You need to create a new array for each location - that part of the trick!

      for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){ 

        inventory[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0};

      };//end inventory loop

      shop_location[list_of_locations[location_index]] = {"city":list_of_locations[location_index],inventory};

  }//end location loop

  calendar[day_of_sales] = {"Day": day_of_sales, shop_location};

}//end calendar loop

//check your work
console.log('calendar:'); console.log(calendar);
console.log('shop_location:'); console.log(shop_location);
console.log('specific information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//returns 'BMW'
console.log('change Dayton.BMW information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand="Triumph");//change value
console.log('check work (Dayton.BMW): '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//check work - PASS
console.log('check work (Cincinnati.BMW): '); console.log(calendar[1].shop_location["Cincinnati"].inventory["BMW"].brand);//check work other location - PASS!!

//Make some lasting and specific changes
console.log("Now make a change in the month value over showing a sale on the 13th");
var sale_date = 13;
console.log("date of sale " + sale_date + "th");

var original_number_on_hand = calendar[sale_date].shop_location["Dayton"].inventory["BMW"].on_hand;
console.log("original_number_on_hand on that date: " + original_number_on_hand);

var number_of_units_sold = 3;
console.log("number_of_units_sold on that date: " + number_of_units_sold);

var new_inventory_level = original_number_on_hand - number_of_units_sold;
console.log("new_inventory_level: " + new_inventory_level);

for(date_index = sale_date; date_index  <= DAYS_IN_A_MONTH; date_index ++){  
  calendar[date_index].shop_location["Dayton"].inventory["BMW"].sold = number_of_units_sold;
  calendar[date_index].shop_location["Dayton"].inventory["BMW"].on_hand = new_inventory_level;
}

console.log("Show change in inventory");
  console.log(list_of_locations[0]+" has " + calendar[10].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[10].shop_location["Cincinnati"].inventory["BMW"].on_hand);
  console.log(list_of_locations[0]+" has " + calendar[11].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[11].shop_location["Cincinnati"].inventory["BMW"].on_hand);
  console.log(list_of_locations[0]+" has " + calendar[12].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[12].shop_location["Cincinnati"].inventory["BMW"].on_hand);
  console.log(list_of_locations[0]+" has " + calendar[13].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[13].shop_location["Cincinnati"].inventory["BMW"].on_hand);
  console.log(list_of_locations[0]+" has " + calendar[14].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[14].shop_location["Cincinnati"].inventory["BMW"].on_hand);
  console.log(list_of_locations[0]+" has " + calendar[15].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[15].shop_location["Cincinnati"].inventory["BMW"].on_hand);
  console.log(list_of_locations[0]+" has " + calendar[16].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[16].shop_location["Cincinnati"].inventory["BMW"].on_hand);

  //add new items to a shop inventory
var inventory_2 =[];
for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){ 

  inventory_2[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0};

};//end inventory loop
console.log("show inventory_2");console.log(inventory_2);
console.log("add inventory");inventory_2["Indian"] = {"brand": "Indian", "on_hand": 10,"sold": 0};
console.log("show updated inventory_2");console.log(inventory_2);

</script>
</head>
<body>
  <p>look in the JavaScript console for output</p>
</body>
</html>

      

0


source







All Articles