【问题标题】:Javascript What method should I use to find or check if a string exists in an array?Javascript 我应该使用什么方法来查找或检查数组中是否存在字符串?
【发布时间】:2015-03-02 16:42:05
【问题描述】:

我找到了这些方法,indexOf() 显然不适用于 Internet Explorer 8

有很多选择,我想知道哪一个是事实,或者我应该选择使用什么以获得最佳效果。

另外,如果结果是undefined,我该如何使用它作为值,我只是将它用作像“undefined”这样的字符串还是为空?

array.find() 
array.findIndex()
array.indexOf("string");

在这个知道索引的数组中替换字符串的示例中,他们使用 indexOf,我应该担心不兼容吗?

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

【问题讨论】:

标签: javascript arrays string find


【解决方案1】:

对这些类型的东西使用 polyfill 是完全可以接受的:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill

if (!Array.prototype.indexOf) {
    // paste polyfill here
}

您还可以使用不同库提供的方法:

// jQuery
if ($.inArray("some_value", someArray) > -1) { ... }

// Underscore
if (_.contains(someArray, "some_value")) { ... }

【讨论】:

  • 那些是保留字? array.prototype 并感谢您的回答
  • 我不确定您对保留字的要求。 indexOf 从 ECMA 5 开始当然是保留的——但是 IE8 没有实现 ECMA 5,因此 indexOf 在那个浏览器中并不是真正的“保留”。 Polyfilling 是一种将现代功能引入旧版浏览器的技术。您可以填充数百种东西 - 但我建议只做您需要的东西。
  • 我指的是array.prototype,我在MDN上遇到过它,我想知道这是否仅适用于那个实例,例如。原型这个词,但你也提到了。
  • 啊,我明白了。 Array(大写“A”)是 javascript 数组的“构造函数”对象。创建 Array 构造函数的“实例”很简单:var my_array = [],它与var my_array = new Array() 基本相同。 Javascript 构造函数有一个特殊的prototype 属性,它是由每个实例继承的方法和属性的集合。由于indexOf 是在Array.prototype 上定义的,my_array 可以使用该方法:my_array.indexOf(...);
猜你喜欢
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2017-10-30
  • 2021-12-27
  • 2021-12-28
  • 2022-08-07
  • 1970-01-01
相关资源
最近更新 更多