2017-05-03 60 views
0

我知道這個問題已經存在了一段時間,但是我還沒有找到可以解決我的問題的答案(對不起,如果我錯過了)。jshint - 不要在一個循環內使用Array.find創建函數

不管怎麼說,我有以下代碼:

for(let i=0; i<array.length; i++) { 
    let value = array[i]; 
    let anotherValue = anotherArray.find(val => val.key === value.key); 
} 

該代碼使得jshint拋出警告:不要在循環中做功能。 (W083)

事實上,我需要訪問「for」範圍內的變量,這讓我需要在其中聲明一個函數。

我曾嘗試以下方法:

let myFunc = (val) => { 
    //no value here to compare 
} 
for(let i=0; i<array.length; i++) { 
    let value = array[i]; 
    let anotherValue = anotherArray.find(myFunc); 
} 

如果我宣佈它外面我無法訪問變量。爲了

array.forEach((value) => { 
    let anotherValue = anotherArray.find(val => val.key === value.key); 
    /* do anything with anotherValue */ 
} 

或者,您可以curry your function能夠採取value,仍然有一個功能:

+0

只需關閉該警告消息。 – 2017-05-03 18:18:51

+0

問題根本不在於消息。這將很容易擺脫。我只是認爲它必須是一個更好的實現。 –

+1

你的實現是絕對好的。 – 2017-05-03 19:04:49

回答

1

嘗試使用Array.forEach代替for -loop

let myFunc = candidate => target => candidate.key === target.key; 
for (let i = 0; i < array.length; i++) { 
    let anotherValue = anotherArray.find(myFunc(array[i])); 
} 

然而交替,您可以通過向文件頂部添加指令來讓JSHint忽略此文件中的此規則:

/* jshint loopfunc: true */ 
+1

咖喱方法也會在循環的每次迭代中生成一個函數。 –

+0

這樣做,我只是不認爲jshint會抱怨它,因爲「函數發生器」定義在循環之外。雖然我沒有測試過這個。 –