【问题标题】:Javascript list contains a string [duplicate]Javascript列表包含一个字符串[重复]
【发布时间】:2016-12-13 18:06:51
【问题描述】:

有谁知道不使用 indexOf 来检查列表是否包含字符串的方法?在我的数组中,一些字符串可以包含其他字符串的一部分,因此 indexOf 会产生误报。

例如,如何确定“组件”是否在下面的数组中?

["component.part", "random-component", "prefix-component-name", "component"]

更新:

似乎我对误报的使用具有误导性。我的意思是当我想自己匹配字符串时,它会说组件在那里 4 次。

即。在检查以下数组中是否存在“组件”时,它应该返回 false。

["component.part", "random-component", "prefix-component-name"]

【问题讨论】:

  • IndexOf 不会给你误报。它会给你 3. 如果你想找到所有具有“otherstuff componenet”的元素,你可以遍历你的数组并检查String.includes()

标签: javascript


【解决方案1】:

使用Array.find API。

示例:

"use strict";

let items = ["component.part", "random-component", "prefix-component-name", "component"];

let found = items.find(item => { return item === "component.part" } );

if (found) {
    console.log("Item exists.");
}

更多用法示例。

参见: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

【讨论】:

  • 我想他想找到所有包含“组件”的元素。
  • @YasinYaqoobi 这个问题有点不清楚,听起来确实需要在错误中搜索包含单词组件的项目。我已经包含了另一个解决方案。见下文。
  • 我显然让自己不清楚,我只想匹配确切的字符串“组件”。该示例旨在说明为什么我不能只使用 indexOf。
  • 当我尝试使用它时,它却说“'string[]'类型上不存在属性'find'”。
  • @annedroidid find api 仅适用于 Javascript 数组。 String[] 听起来 java 对我来说。是否愿意在问题区域中显示您更新的代码,以便我跟进?
【解决方案2】:

一种方法是使用.find() 从数组中获取您想要的字符串。

【讨论】:

    【解决方案3】:

    尝试使用 $.inArray() 方法。

    var list=["component.part", "random-component", "prefix-component-name", "component"];
    if($.inArray(" component",list) != -1){
        console.log("Item found");
    }
    

    【讨论】:

      【解决方案4】:

      有谁知道不使用 indexOf 来检查列表是否包含字符串的方法?在我的数组中,一些字符串可以包含其他字符串的一部分,因此 indexOf 会产生误报。

      误报? Array.prototype.indexOfArray.prototype.includes 都使用严格相等,这使得这里不可能。

      【讨论】:

        【解决方案5】:

        IndexOf 不会给您误报。它会给你 3。如果你想找到所有具有“其他组件”的元素,你可以遍历你的数组并检查 String.includes()

        这是一个适合初学者的解决方案。

            var arr = ["component.part", "random-component", 
            "prefix-component-name", "component", "asdf"]; 
            
            console.log(arr.indexOf('component')); // give u 3
            
            for (var i = 0; i < arr.length; i++){
              if (arr[i].includes('component')){
                console.log(arr[i]);
              }
            }

        【讨论】:

          猜你喜欢
          • 2011-08-31
          • 2012-12-06
          • 1970-01-01
          • 1970-01-01
          • 2013-09-12
          • 2019-03-15
          • 2011-08-28
          • 2020-06-17
          • 1970-01-01
          相关资源
          最近更新 更多