简体   繁体   English

我可以用 if 在一行上写箭头 function

[英]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.你不能这样做,因为无论你写什么,find 都会检查回调的返回值是真还是假。 What is returned from the callback is processed internally and returns the item inside find not the callback function.回调返回的内容在内部处理并返回里面的项目而不是回调 function。 IndexOf basically does what you want. IndexOf 基本上可以满足您的需求。

If you really want to use an arrow function, you can do this.如果你真的想使用箭头 function,你可以这样做。

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

However, this is unneccessary.然而,这是不必要的。 You can simply use indexOf :您可以简单地使用indexOf

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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