简体   繁体   中英

Can I write arrow function with if on a single line

For example, I have an array:

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

I want to find and return the index of 'pens' in the array, how can I write something like:

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

You can't do that, since find checks the returned value of callback as true or false, whatever you write. What is returned from the callback is processed internally and returns the item inside find not the callback function. IndexOf basically does what you want.

If you really want to use an arrow function, you can do this.

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

However, this is unneccessary. You can simply use indexOf :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM