分配给基元的值将丢失 [英] Value assigned to primitive will be lost

查看:953
本文介绍了分配给基元的值将丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个对象数组,并循环遍历它们为每个对象分配一个属性值,WebStorm警告我:

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'
    }
];

没有函数包装器:

people.forEach(function (person) {
    person.surname = 'Baz'; // No error. Works in console.
});

使用函数包装器:

function changeSurname(people) {
    people.forEach(function (person) {
        person.surname = 'Baz'; // Error warning me that value assigned to primitive will be lost.
    });
}

changeSurname(people);

这两个都在控制台中产生相同的输出(姓氏改为'baz')。

Both of these produce the same output in the console (the surname is changed to 'baz').

我认为这与对象引用和 person 指向的内容有关,但我不确定究竟是什么。

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?

WebStorm试图拯救我的潜在错误是什么?

What potential bug is WebStorm trying to save me from?

推荐答案

你的代码没有任何不当之处,WebStorm的类型推断有点混乱(JavaScript的这方面特别令人困惑) 。

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

它的linter看到一个字符串并假设你会尝试这样的事情:

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

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

primitive.vowels;
// => undefined

哪会导致'丢失'值。

事实上它只是捕获函数内部的'错误'似乎是一个应该报告的彻头彻尾的错误。

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

为了进一步理解这个奇怪的JavaScript部分,我推荐Angus Croll的优秀深度文章这里

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

这篇关于分配给基元的值将丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆