简体   繁体   中英

Javascript for() to add values to array

I have a program that displays errors like this:

wifi : 298

So, it says the type of error and the number.

Right now there are 8 errors, which I have divided by type and number, so 16 values. I would like to add them to an array like:

var array{type:'____', number:'____'}

I would like to add the values via function, so it can be automatic, in case I add ou remove errors to display, a for seems the best way to do it.

Problem is.. I'm horrible at math..

I've tried a for where i starts at -1 and its i++. The type would be value[i+1] and the number would be value[i+2]. This would be the result:

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

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

So you see, value[1] appears twice: 0 1 1 2

When it should only appear once: 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]};
}

Just up it by 2 on every iteration. I would also suggest slight changes for readability (Replacing -1 by 0 and changing index acccessors).

You need to make the errors array an actual array and add things to it not overwriting them.

You can make the loop variable length too by just using the errorSplit length as a limiter.

 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
 }

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