簡體   English   中英

我可以用 if 在一行上寫箭頭 function

[英]Can I write arrow function with if on a single line

例如,我有一個數組:

arr= ['notebook', 2, 'pens', 'bags', newElement]

我想在數組中查找並返回“筆”的索引,我該如何寫:

let found = arr.find(item => arr.indexOf(item) if item =='pens')
return arr.indexOf(
 arr.find(item => item =='pens')
);

你不能這樣做,因為無論你寫什么,find 都會檢查回調的返回值是真還是假。 回調返回的內容在內部處理並返回里面的項目而不是回調 function。 IndexOf 基本上可以滿足您的需求。

如果你真的想使用箭頭 function,你可以這樣做。

let found = arr.findIndex(item => item =="pens");

然而,這是不必要的。 您可以簡單地使用indexOf

let found = arr.indexOf("pens");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM