我在使用 .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/