If I have an array of objects, and loop through them assigning a value to an attribute for each one, WebStorm warns me:
Values assigned to primitive will be lost
However, when testing in the console, I do not "lose" any values.
This only happens when the loop is inside of a function.
An example of this error below:
let people = [
{
name: 'Foo',
age: 21,
surname: 'FooBar'
},
{
name: 'Bar',
age: 51,
surname: 'FooBar'
}
];
Without function wrapper:
people.forEach(function (person) {
person.surname = 'Baz'; // No error. Works in console.
});
With function wrapper:
function changeSurname(people) {
people.forEach(function (person) {
person.surname = 'Baz'; // Error warning me that value assigned to primitive will be lost.
});
}
changeSurname(people);
Both of these produce the same output in the console (the surname is changed to 'baz').
I assume this has something to do with the object reference and what person
points to, but I am not sure exactly what.
Why do I see this error?
What potential bug is WebStorm trying to save me from?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…