![](/img/trans.png)
[英]How to get matches string element from array in angular or javascript
[英]How to get indexOf that matches this string from an array in javascript
我想做的是:如果數組包含foo,則從數組中獲取foobar
我通常只使用indexOf ,但是這次我沒有確切的字符串,也不知道要使用include函數
這是我的代碼示例:
var array = "Hello world, welcome to the universe.";
var str = array.split(" ");
var foobar = str.indexOf(this.includes("uni"));
您可以改用Array.find()
,它返回給定謂詞返回true
的第一項。 如果數組中沒有項滿足該謂詞,則.find()
的結果將為null
。
var array = "Hello world, welcome to the universe."; var str = array.split(" "); var foobar = str.find(word => word.includes("uni")); //Find first word that includes "uni" console.log(foobar);
如果您正在尋找索引,這應該可以為您提供索引。
var array = "Hello world, welcome to the universe.";
var str = array.split(" ");
var foobar = str.indexOf(str.find(word => word.includes("uni")));
console.log(foobar);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.