2017-05-05 79 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錯誤