【问题标题】:Javascript multidimensional array updating specific elementJavascript多维数组更新特定元素
【发布时间】:2012-04-16 07:09:24
【问题描述】:

我有一个字符串已经在js中转换成二维数组。

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

用来表示棋盘

每个 .代表一个空格

每个 |代表一行

每个 X 代表一堵墙

编辑:下面的二维数组创建代码

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'

                    

当我访问 board[i][j] 时,它会正确返回:

[0][0] = "."

[1][1] = "X"

[1][2] = "."

等等等等

我想用代表一块的字符串更新特定元素。 但是,当我像这样插入元素时:

board[0][0] = "piece4"

数组在 firebug 中返回如下:

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

什么时候应该是这样的:

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

为什么元素 [0][1] 和 [0][2] 会被覆盖?我在 js 中没有正确理解数组索引访问的数组吗?

【问题讨论】:

  • 它们应该从 (0,0) 开始
  • 我在您的示例代码中只看到一维字符串。那些二维数组在哪里?所示代码 - 将字符串分配给 var "board" 然后使用 [0][0] 访问它 - 根本不起作用(返回未定义 - 自然!)。
  • 没有代码,无法证明数组确实具有您认为的结构。因此,请同时包含数组/代码。
  • 那么你是如何从数组中取回字符串的?
  • 如果您去了a = 1; 和后来的a = 2,您不会期望 a 为 3,为什么您会期望数组中有任何不同?

标签: javascript multidimensional-array


【解决方案1】:

我刚刚遇到了同样的问题,但它有一个更复杂的原因,我想添加它,以防有人发现此页面搜索我遇到的相同问题:

我已经创建并填充了一个这样的二维数组:

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

创建一个用零填充的二维 n*n 数组。

现在当我试图覆盖这样的单元格时

foo[1][1] = 1;

我最终得到了这些值:

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

恕我直言,这真是令人惊讶。

这样做的原因是,只有 一个 行,它在内部被引用 3 次。因此,当我更改“第二”行中的第一个索引时,它实际上更改了所有行。

底线:不要使用Array.fill 创建多维数组!

【讨论】:

  • 太糟糕了! fill() 似乎是创建二维零填充数组的完美方式,直到我遇到完全相同的问题。
  • 出色的语言行为.. 在找到您的答案之前,我一直在质疑自己对这个问题的理智。谢谢你,先生!
  • 我在创建多维数组时也遇到了这个问题,但是我使用 .push() 创建了数组。使用 .push() 创建多维数组时如何克服这个问题。
  • 谢谢你。挠了我的头一个小时。以为我快疯了。
  • 谢谢,你拯救了我的一天,我尝试了一切,但没有任何效果。
【解决方案2】:

问题:

我打赌你有一个一维数组,每个数组中都存储了字符串。所以你的数组实际上看起来像:

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

当这是你想要的:

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


解决方案:

在构造二维数组时,请确保将board 中的每个条目显式声明为数组。因此,要构建它,您的代码可能如下所示:

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

【讨论】:

  • 谢谢,我相信这就是问题所在。我的字符串解析成二维数组循环不正确。
【解决方案3】:

在 javascript 中创建二维数组的另一种方法是使用 Array.from 函数

  var 2Darr =  Array.from(Array(5), () => {
                 return new Array(5).fill(0)
             })

这将创建一个完全用 0 填充的 5 x 5 数组。Array.from 有两个参数,第一个是用于从中提取数组的 javascript 可迭代对象,第二个是可选回调,我们可以在其中指定要应用于数组元素。

访问元素可以像其他语言一样简单地完成。

【讨论】:

    【解决方案4】:

    这里有两点说明:

    1. 数组从每个维度的索引 0 开始。
    2. 如果将字符串作为二维数组访问,则每个元素都是 char 而不是字符串。

    所以如果你写board[0][0] = 'X';,那么你会得到正确的行为(这会改变字符串的第一个字符,而不是第二个)。

    【讨论】:

      【解决方案5】:

      上面给出的情况和解决方案非常简单。更新对象列表(通常称为数组,但这是不同时间的讨论)中的特定值的问题具有更实际和工业应用。您倾向于遇到的问题是认为查看特定单元格中的值,例如my_array[0][0] 返回 'some value' 还可以让您通过赋值来更改该值,例如my_array[0][0] = '新值'。您会发现,根据您定义数组的方式,更改显示在各列的同一行中,而不是您需要的。 查看示例代码作为创建和管理对象(数组)的多维列表的说明。

      <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's 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's 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's 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's 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 2016-08-11
        相关资源
        最近更新 更多