发布元素正确的一些(元素)

时间:2019-05-16 13:11:13

标签: javascript

我有这段代码可以检查数组中的元素并确定它们的存在(真,假),但是我想知道哪个元素存在,我该如何实现呢? 输出应为:true,嗨 代码:

var str1 = 'hi, how do you do?';

// does the test strings contains this terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests agains every element in the array
var test1 = conditions.some(el => str1.includes(el));
document.write(str1, ' ===> ', test1);

- 预先感谢。

1 个答案:

答案 0 :(得分:3)

您可以使用find()代替some()

注意: find()将仅获得与条件匹配的数组的单个(第一个)元素。如果没有条件匹配,则返回undefined

var str1 = 'hi, how do you do?';

// does the test strings contains this terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests agains every element in the array
var test1 = conditions.find(el => str1.includes(el));
console.log(test1)

如果要获取匹配条件的数组的所有元素,请使用filter()

var str1 = 'hi, how do you do? howdy';

// does the test strings contains this terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests agains every element in the array
var test1 = conditions.filter(el => str1.includes(el));
console.log(test1)