Whenever I use a forEach loop (or a for loop), the values that I assign to my variables get changed, this is the code I am using:
var myArray = [ { a: 'Val1', b: 'Information Message1' },
{ a: 'Val2', b: 'Information Message2' },
{ a: 'Val3', b: 'Information Message3' } ]
var mainArray = [];
myArray.forEach(function(info) {
let value1 = info.a;
let value2 = info.b;
console.log('Pos 1: ' + value1);
if (!allowedValues.includes(value1)) { value1 = 'Default'; }
if (allowedValues.includes(value1)) {
request.post(
'https://apilink.com/api', {
json: { varA: value1, varB: value2 }
},
function(error, response, body) {
if (!error && response.statusCode == 200) {
mainArray.push(body.value);
console.log('Pos 2' + value1);
} else { console.log(error); }
}
)
}
});
The names will all show up at once for the first time I console.log in the for loop, but the second time I call console.log in the for loop, the array's position is different:
Pos 1: Val1
Pos 1: Val2
Pos 1: Val3
Pos 2: Val2
Pos 2: Val1
Pos 2: Val3