Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Value assigned to primitive will be lost

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's nothing improper in your code, WebStorm's type inference is getting a bit confused (this aspect of JavaScript is particularly confusing).

Its linter sees a string and assumes you will try something like this:

var primitive = "september";
primitive.vowels = 3;

primitive.vowels;
// => undefined

Which would lead to a 'lost' value.

The fact that it only catches this 'error' inside of a function seems like an outright bug that should be reported.

To further understand this weird part of JavaScript, I recommend Angus Croll's excellent in-depth article here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...