浏览器对array.includes和Alternatives的支持 [英] Browser support for array.includes and alternatives
问题描述
我查了一下,发现这与在数组中的较大字符串中查找子字符串有关. Array.Prototype.includes >
I looked it up and found this regarding finding a substring in a larger string in an array. Array.Prototype.includes
if (t.title.includes(searchString))
我的t
是$.each
的一部分,它正在遍历更大的对象数组(每个对象都有来自字符串,日期等的大量信息). searchString
是用户在框中键入的任何内容.所有这些都是我页面上列表的简单搜索功能.
My t
is part of a $.each
that's iterating through a larger array of objects (each objects got a buttload of info, from strings, dates and such). searchString
is whatever the user typed in a box. All this is a simple search function for a list I have on the page.
这在Chrome中可以正常使用.但是Firefox和IE出现错误,指出
This works just fine in Chrome. But Firefox and IE are turning up errors stating
TypeError: currentTicket.title.includes is not a function
所以我要么发出警告信号,表明我的应用程序只能在Chrome上运行,要么手工创建查找功能?奇怪的是我张贴的MDN的文档页面指出只有Firefox支持array.includes
,奇怪的是它只有运行它的Chrome.
So I either put up a warning sign that my app only works on Chrome or I handcraft a find function? Weird thing is the doc page from MDN I posted states that only Firefox supports the array.includes
, strangely enough it's only Chrome that runs it.
推荐答案
与其使用当前标记为实验性"的API,不如考虑使用更广泛支持的方法,例如Array.prototype.indexOf()
(IE也支持该方法) ).
Instead of using an API that is currently marked as "experimental" consider using a more broadly supported method, such as Array.prototype.indexOf()
(which is also supported by IE).
您可以使用t.title.indexOf(string) >= 0
您还可以使用 Array.prototype.filter()
来获得满足特定条件的新字符串数组,如下例所示.
You can also use Array.prototype.filter()
to get a new array of strings that meet a certain criteria, as in the example below.
var arr = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
document.getElementById("input").onkeyup = function() {
document.getElementById("output").innerHTML = arrayContainsString(arr,this.value);
}
document.getElementById("header").innerHTML = JSON.stringify(arr);
function arrayContainsString(array, string) {
var newArr = array.filter(function(el) {
return el.indexOf(string) >= 0;
});
return newArr.length > 0;
}
<input id="input" type="text" />
<br/>
<div>array contains text:<span id="output" />
</div>
<div id="header"></div>
这篇关于浏览器对array.includes和Alternatives的支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!