将1D数组使用WHILE循环映射到2D关联数组,直到数组长度为0之前失败。

huangapple go评论60阅读模式
英文:

Map 1D array to 2D associative array using WHILE LOOP with array.length - fails before length is 0

问题

JavaScript - 我有一个一维数组,我想将其映射到一个二维关联数组['name']['includes']['config']。我正在使用一个while循环。可能有一种更优雅的方法,我欢迎...

我遇到的问题是,在关联数组的索引2处产生了错误,而循环迭代的id_array.length = 3仍然保持不变。我已经包含了一些测试数据。当一维数组中有3或6个项目的集合时,循环正常工作,但当超过9个时,它会失败。数据始终是3的倍数。

循环与以下一起工作:

id_array = ["a0", "b0", "c0"];
id_array = ["a0", "b0", "c0", "a1", "b1", "c1"];

失败于:

id_array = ["a0", "b0", "c0", "a1", "b1", "c1", "a2", "b2", "c2"];

以下是代码:

var id_array = ["a0", "b0", "c0", "a1", "b1", "c1", "a2", "b2", "c2"]; // 使用此集合会失败
console.log(id_array);
console.log(id_array.length);

// 创建关联数组
var units_array = [
  [],
  []
]; // 关联数组
var value = ''; // 要推送到关联数组的内容
var i = 0; // 关联数组的索引
while (id_array.length) {
  console.log('id数组长度:' + id_array.length);
  console.log('i:' + i);
  value = id_array.shift() + "xx 一些其他操作的数据";
  units_array[i]['name'] = value;

  console.log('id数组长度:' + id_array.length);
  console.log('i:' + i);
  value = id_array.shift() + "xx 一些其他操作的数据";
  units_array[i]['includes'] = value;

  console.log('id数组长度:' + id_array.length);
  console.log('i:' + i);
  value = id_array.shift() + "xx 一些其他操作的数据";
  units_array[i]['config'] = value;
  i = i + 1;
}

console.log(units_array);

我在第三次迭代时收到的控制台错误消息是:

Uncaught TypeError: Cannot set properties of undefined (setting 'name')

控制台输出如下:

properties.php:695 (9) ["a0", "b0", "c0", "a1", "b1", "c1", "a2", "b2", "c2"]
0: "b2"
1: "c2"
length: 2[[Prototype]]: Array(0)

properties.php:696 9
properties.php:703 id数组长度9
properties.php:704 i0
properties.php:708 id数组长度8
properties.php:709 i0
properties.php:713 id数组长度7
properties.php:714 i0
properties.php:703 id数组长度6
properties.php:704 i1
properties.php:708 id数组长度5
properties.php:709 i1
properties.php:713 id数组长度4
properties.php:714 i1
properties.php:703 id数组长度3
properties.php:704 i2

我不太明白下面的控制台信息,为什么它显示0:b2,1:c2,长度2(为什么是2?),但似乎在循环中停在那里。但它似乎认识并显示了包含9个项目的数组。

properties.php:695 (9) ["a0", "b0", "c0", "a1", "b1", "c1", "a2", "b2", "c2"]
0: "b2"
1: "c2"
length: 2[[Prototype]]: Array(0)

提前感谢您的帮助!

英文:

Javascript - I have a one dimensional array that I want to map into a 2 dimensional associative array ['name']['includes']['config']. I am using a while loop. There is probably a more elegant way, and would welcome that...

The problem I am having is that it is producing an error on index 2 of the associative array and loop iteration with id_array.length = 3 still remaining. I have included some test data. The loop works fine with a set of 3 or 6 item data in the one dimensional array, but when it gets to 9 or beyond, it fails. The data is always in multiples of 3.

The loop works with:

id_array = ["a0","b0","c0"];
id_array = ["a0","b0","c0","a1","b1", "c1"];

Fails with:

id_array = ["a0","b0","c0","a1","b1","c1","a2","b2","c2"];

Code below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var id_array = [&quot;a0&quot;, &quot;b0&quot;, &quot;c0&quot;, &quot;a1&quot;, &quot;b1&quot;, &quot;c1&quot;, &quot;a2&quot;, &quot;b2&quot;, &quot;c2&quot;]; //fails with this set
console.log(id_array);
console.log(id_array.length);

//create associative array
var units_array = [
  [],
  []
]; //associative array
var value = &#39;&#39;; //content to push into associative array
var i = 0; //index of associative array
while (id_array.length) {
  console.log(&#39;id array length: &#39; + id_array.length);
  console.log(&#39;i: &#39; + i);
  value = id_array.shift() + &quot;xx some other manipulated data&quot;;
  units_array[i][&#39;name&#39;] = value;

  console.log(&#39;id array length: &#39; + id_array.length);
  console.log(&#39;i: &#39; + i);
  value = id_array.shift() + &quot;xx some other manipulated data&quot;;
  units_array[i][&#39;includes&#39;] = value;

  console.log(&#39;id array length: &#39; + id_array.length);
  console.log(&#39;i: &#39; + i);
  value = id_array.shift() + &quot;xx some other manipulated data&quot;;
  units_array[i][&#39;config&#39;] = value;
  i = i + 1;
}

console.log(units_array);

<!-- end snippet -->

The console error message I get on the 3rd iteration is:

> Uncaught TypeError: Cannot set properties of undefined (setting 'name')

Console readout is:

properties.php:695 (9)&#160;[&#39;a0&#39;, &#39;b0&#39;, &#39;c0&#39;, &#39;a1&#39;, &#39;b1&#39;, &#39;c1&#39;, &#39;a2&#39;, &#39;b2&#39;, &#39;c2&#39;]
0: &quot;b2&quot;
1: &quot;c2&quot;
length: 2[[Prototype]]: Array(0)

properties.php:696 9
properties.php:703 id array length: 9
properties.php:704 i: 0
properties.php:708 id array length: 8
properties.php:709 i: 0
properties.php:713 id array length: 7
properties.php:714 i: 0
properties.php:703 id array length: 6
properties.php:704 i: 1
properties.php:708 id array length: 5
properties.php:709 i: 1
properties.php:713 id array length: 4
properties.php:714 i: 1
properties.php:703 id array length: 3
properties.php:704 i: 2

I don't quite understand the console info below, why it shows 0:b2, 1:c2, length 2 (why 2?), but seems like that is where it stops at in the loop. But it does seem to recognize and show the 9 item array...

properties.php:695 (9)&#160;[&#39;a0&#39;, &#39;b0&#39;, &#39;c0&#39;, &#39;a1&#39;, &#39;b1&#39;, &#39;c1&#39;, &#39;a2&#39;, &#39;b2&#39;, &#39;c2&#39;]
0: &quot;b2&quot;
1: &quot;c2&quot;
length: 2[[Prototype]]: Array(0)

Thanks in advance!

答案1

得分: 0

Initialize units_array like this:

units_array 这样初始化:

var units_array = [];

Then at the top of the while loop:

然后在 while 循环的顶部:

while (id_array.length) {
    console.log('id array length: ' + id_array.length);
    console.log('i: ' + i);
    units_array.push([]);
    // ...
}

That way every three elements you'll add a new sub-array to unit_array.

这样,每三个元素,你都会向 unit_array 添加一个新的子数组。

Because you're using property names that are not numeric, your sub-arrays in units_array won't work properly in a lot of situations (like JSON.stringify()). Instead, you can use objects:

因为你使用的属性名称不是数字,所以在许多情况下,units_array 中的子数组不会正常工作(比如 JSON.stringify())。相反,你可以使用对象:

let units_array = [];
while (id_array.length) {
    units_array.push({});
    // ...
}

That'll leave you with an array of objects. I would not use the term "associative array" for this, as units_array is a plain array with numeric indexes. JavaScript doesn't really have an associative array type. Objects and Map instances are close, but they're not intended to work like associative arrays in languages that explicitly support them.

英文:

Initialize units_array like this:

var units_array = [];

Then at the top of the while loop:

   while (id_array.length) {
      console.log(&#39;id array length: &#39; + id_array.length);
      console.log(&#39;i: &#39; + i);
      units_array.push([]);
      // ...

That way every three elements you'll add a new sub-array to unit_array.

Because you're using property names that are not numeric, your sub-arrays in units_array won't work properly in a lot of situations (like JSON.stringify()). Instead, you can use objects:

let units_array = [];
while (id_array.length) {
  units_array.push({});
  // ...

That'll leave you with an array of objects. I would not use the term "associative array" for this, as units_array is a plain array with numeric indexes. JavaScript doesn't really have an associative array type. Objects and Map instances are close, but they're not intended to work like associative arrays in languages that expli

答案2

得分: 0

var units_array = [
  [],
  []
]

你创建了一个包含两个数组的数组(应该是对象,不好意思,这不是PHP),所以当你尝试使用9个项目时,你试图使用units_array中的第3个索引,但该索引是undefined。因此,代码失败了。

你可以简化代码如下:

const arr = ["a0", "b0", "c0", "a1", "b1", "c1", "a2", "b2", "c2"]; // 使用此集合会失败

const result = [];

for (let i = 0; i < arr.length; i += 3) {
  result.push({
    name: arr[i],
    includes: arr[i + 1],
    config: arr[i + 2],
  });
}

console.log(result);

<details>
<summary>英文:</summary>

var units_array = [
[],
[]
]

You created an array with 2 arrays (which should be objects btw, that&#39;s not PHP, sorry), so when using 9 items you try to use the 3d index in `units_array` which is `undefined`. So the code fails.

You could simplify the code:


&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    const arr = [&quot;a0&quot;, &quot;b0&quot;, &quot;c0&quot;, &quot;a1&quot;, &quot;b1&quot;, &quot;c1&quot;, &quot;a2&quot;, &quot;b2&quot;, &quot;c2&quot;]; //fails with this set

    const result = [];

    for(let i = 0; i &lt; arr.length; i += 3) {
      result.push({
        name: arr[i],
        includes: arr[i+1],
        config: arr[i+2]
      });
    }

    console.log(result);





&lt;!-- end snippet --&gt;



</details>



huangapple
  • 本文由 发表于 2023年6月8日 04:22:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定