【问题标题】:Is String.contains a standard function in JavaScript?String.contains JavaScript 中的标准函数吗?
【发布时间】:2015-05-21 08:36:51
【问题描述】:

最近我在用 JavaScript 写逻辑,写了这样的东西

var str="hello world";

if(str.contains("w"))
    //do something
else
   //do anotherthing

在我在 Chrome 中运行该页面之前,我认为它运行良好。在 Chrome 中,我收到contains is not a function 的错误。

虽然我通过将逻辑修改为

来摆脱它

var str="hello world";
if(str.indexOf("w")!=-1)
    //do something
else
   //do another thing

contains 不是标准的 ECMAScript 函数吗?我可以在 Firefox 中通过智能感知看到 contains,但在 Chrome 中看不到。

在不同的浏览器中测试这些时,我在控制台中注意到

String.subString/indexOf //not showing in chrome but works in Firefox

而不是 str.substring/indexOf 在 chrome 中工作

这些方法不是标准String 对象的一部分吗?

【问题讨论】:

标签: javascript google-chrome standard-library ecmascript-harmony


【解决方案1】:

解释here。 String.prototype.contains 不是当前发布的 EsmaScript 5.1 的一部分。

【讨论】:

【解决方案2】:

这是this问题的重复。

为方便起见,我将在此处重新发布答案。

现在默认禁用 Firefox 和 Chrome 对此的支持。如果您登陆这里寻找最新的答案,您可以查看原因以及新方法名称(即 String.includes)here。

试试:

yourString.includes('searchString')

【讨论】:

    【解决方案3】:

    .contains() 不是标准字符串对象的一部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 2016-05-03
      • 1970-01-01
      • 2011-08-01
      • 2011-06-19
      • 2012-05-17
      相关资源
      最近更新 更多