2017-05-05 148 views
3

我有一个对象ESLint不允许在

currentValues= {hey:1212, git:1212, nmo:12121} 

,我在使用这样的:

for (const key in currentValues) { 
    if (Object.prototype.hasOwnProperty.call(currentValues, key)) { 
     yield put(setCurrentValue(key, currentValues[key])); 
    } 
} 

ESLint显示我这是说的错误:

ESLint:for..in循环遍历整个原型链,这实际上从来不是你想要的。使用对象{键,值,条目},并遍历结果数组。 ?(没有限制的语法

应该如何修改我的代码

+2

尝试'为(currentValues.keys的常量键())'corrent如果你只需要按键。如果你需要键和值,你可以使用'entries'。 – Li357

+0

@AndrewLi你在谈论Object.keys()吗?如果是这样,那么它就会成为问题,因为用'for ... in'来遍历一个数组是不被接受的。 – Pointy

+1

@Pointy我正在使用'for ... of'? – Li357

回答

-1

使用for...in会遍历所有属性包括那些从对象的原型,我不知道为什么你正在做Object.prototype.hasOwnProperty.call(currentValues, key) 而不只是: currentValues.hasOwnProperty(key)。 我想,这应该让ESLint意识到你正在筛选只有自己的属性。

不过,我建议使用for (const key of Object.keys()),这是更多的语义。

+0

使用来自Object的'hasOwnPrototype(..)'更好。请参阅http://eslint.org/docs/rules/no-prototype-builtins – ronapelbaum

1

你可以得到你的对象里面的所有值的阵列只是在做

var myValuesInArray = Object.values(currentValues); 
1

它说,

使用对象。{键,值项},并迭代产生 阵列。

所以你可以做这样的事情来获得对象键作为数组,然后通过键循环进行必要的更改。

currentValues= {hey:1212, git:1212, nmo:12121} 
 

 
Object.keys(currentValues).forEach(function(key) { 
 
    yield put(setCurrentValue(key, currentValues[key])); 
 
})

3

我用这个:

const keys = Object.keys(currentValues); 
     const values = Object.values(currentValues); 
     for (let i = 0; i <= keys.length; i += 1) { 
      yield put(setCurrentValue(keys[i], values[i])); 
     } 

这是没有eslint错误