Value assigned to primitive will be lost

前端 未结 4 1397
感动是毒
感动是毒 2020-12-17 08:09

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 w

相关标签:
4条回答
  • 2020-12-17 08:17

    I faced similar issue with angular custom directive.

    below was my custom directive:

    function customDirective() {
          return {
            scope: {
              model: '='
            }
            link: function(scope) {
                    scope.resetModel = function() {
                        scope.model.name = null;   //In these lines I was getting the above 
                        scope.model.email = null;  //mentioned warning in webstorm.
                    }
                }
          }
    }
    

    After going through the $compile docs, I decided to use the below code which solves this warning and works fine with the binding to child and parent scopes, yes of course unless until your model is an object reference.

    function customDirective() {
           return {
             scope: {
                model:'<' // Please refer the above linked angular docs for in detail explanation.
             }
             link: function(scope) {
                scope.resetModel = function() {
                   scope.model.name = null;
                   scope.model.email = null;
                }
             }
          }
    }
    
    0 讨论(0)
  • 2020-12-17 08:31

    I just had the same issue.

    You can also ask WebStorm to disable inspection for the next line, but I decided to use a for of loop instead:

    for (person of people) {
        person.surname = 'Baz';
    }
    

    It actually made my code more readable as a result so I was happy.

    0 讨论(0)
  • 2020-12-17 08:36

    If you will use square brackets the JetBrains editor(WebS/PhpS) will not show you any error.

    person['surname'] = 'Baz';
    
    0 讨论(0)
  • 2020-12-17 08:38

    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.

    0 讨论(0)
提交回复
热议问题