簡體   English   中英

在數組中查找某些字符串(JavaScript)

[英]Finding certain strings in array (Javascript)

我在數組搜索中遇到問題。 我想檢查某個元素中是否存在某個字符串,例如

陣:

["4_1", "4_2", "4_3"]

我將檢查字符串“ 4”是否存在於變量之一中。

謝謝!

您可以為此使用循環。

 var arr = ["4_1", "4_2", "4_3"]; search = RegExp(4), result = arr.some(search.test.bind(search)); document.write(result); 

最簡單的方法是使用Array.prototype.join && indexOf方法

["4_1", "4_2", "4_3"].join("").indexOf("4")

更新

根據@ t.niese的評論,此答案可能會導致錯誤的結果,例如,如果您正在查找14 ,它將返回2這是錯誤的,因為您的數組不包含以14開頭的元素。 在這種情況下,最好使用["4_1", "4_2", "4_3"].join(" ").indexOf("14") // -1的答案,或者您可以通過其他方式將其加入["4_1", "4_2", "4_3"].join(" ").indexOf("14") // -1

您實際上可以進行循環並檢查indexOf不為-1

 ["4_1", "4_2", "4_3"].forEach(function (element, index, array) { if (element.indexOf(4) != -1) alert("Found in the element #" + index + ", at position " + element.indexOf(4)); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM