javascript - 使用 .find 或 .find 内部的 .index

标签 javascript arrays

我在使用 .includes 作为 find 函数中的条件时遇到问题。

var a = ["a.example", "b.example1", "c.example2"];
var b = "example1";
a[1].includes(b)
>> true
a[1].indexOf(b)>-1
>>true
a.find( c => { c.includes(b) });
>>undefined
a.find( c => { c.indexOf(b) > -1 });
>>undefined 

我的理解是,如果没有一个数组元素符合条件,则 find 返回 undefined,或者返回第一个符合条件的数组元素。但我无法让这个条件发挥作用。难道我做错了什么?我希望 find 返回真实的 "b.example1"

最佳答案

由于 .find() 回调中充满了使用大括号的箭头函数,因此将 return 语句放入回调中。

a.find(c => { return c.includes(b) });
a.find(c => { return c.indexOf(b) > -1 });

或者完全删除它。

a.find(c => c.includes(b));
a.find(c => c.indexOf(b) > -1);
<小时/>

如需进一步说明,请查看 MDN 上的箭头函数引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

关于javascript - 使用 .find 或 .find 内部的 .index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60324013/

相关文章:

javascript - 函数返回错误 (ESLint) 将函数移动到主体根

javascript - 将大词典复制粘贴到 chrome 控制台

python - NumPy 中时间和空间高效的数组乘法

javascript - 如何检查一个数组是否包含另一个数组?

java - 如何制作字符数组扫描仪?

arrays - 带有 int 数组参数的 EF ExecuteSqlCommand

javascript - 无法更新 THREE.DirectionalLight 的方向

Javascript 数组与 Php 数组

javascript - 具有粘性标题和水平滚动的多个表

计算数组中字符出现的次数