请教一个js数组方法,条件成立返回成立的数组终止循环。

比方说a数组

[
{a:1},
{a:2},
{a:3}
]

我希望判断a=2的时候直接返回{a:2}
之前用a.find(item=> item.a===2) 但是他执行到第二个对象并没有停止一直执行到第三个

阅读 2.1k
2 个回答

会停止的。

image.png


https://developer.mozilla.org...

The find method executes the callback function once for each index of the array until the callback returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns undefined.

...直至有一个 callback 返回 true。当找到了这样一个元素后,该方法会立即返回这个元素的值...

通过throw error可以

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题