Javascript for()向数组添加值

时间:2019-04-11 08:48:45

标签: javascript

我有一个显示如下错误的程序:

  

wifi:298

所以,它说明了错误的类型和数量。

现在有8个错误,我已按类型和数字进行了划分,因此有16个值。我想将它们添加到像这样的数组中:

  

变量数组{type:'____',数字:'____'}

我想通过函数添加值,因此它可以是自动的,以防万一我添加或删除要显示的错误, for 似乎是最好的方法。

问题是..我在数学上很恐怖..

我已经尝试过从-1及其i ++开始的地方。类型为value [i + 1],数字为value [i + 2]。 结果将是:

i=-1
type=value[0]
number=value[1]

i=0
type=value[1]
number=value[2]

因此,您看到value [1]出现了两次: 0 1个 1个 2

仅应出现一次时: 0 1个 2 3

var errorSplit = errorlog.split(/:|;/);

 var errors;

 for(var i=-1;i<16;i++){
    errors= {type: errorSplit[i+1], num: errorSplit[i+2]};
}

1 个答案:

答案 0 :(得分:0)

每次迭代将其增加2。我还建议对可读性进行一些更改(将-1替换为0并更改索引的访问量)。

您需要将errors数组变成实际数组,并向其中添加内容,而不要覆盖它们。

您也可以仅通过使用errorSplit长度作为限制器来使循环的长度可变。

 var errorSplit = errorlog.split(/:|;/);

 var errors=[]; // Make the array an actual array

 for(var i=0; i<errorSplit.length; i+=2) { // Start at index 0, go until there are no errorSplit parts left, up it by 2 every iteration
    if(errorSplit.length<(i+1)) // If the index is higher than errorSplit+1, exit the loop
       break;
    errors.push({type: errorSplit[i], num: errorSplit[i+1]}); // Add the element to the array
 }