如何找出字符串Element?

时间:2019-01-04 06:17:56

标签: javascript

我想找出数组中存在或不存在的字符串元素。 换句话说,我可以解释我要搜索的内容。 在下面的代码中,如果我将“文本”传递给函数,那么如何找出组成“文本”数组的每个元素的索引。 那就是数组,我想打印存在于elements数组中的text元素的索引,但是条件是我们只需要在参数中传递文本即可。

"steps": [
  {
    "stepname": "Step 1",
    "stepnum": 1,
    "elements": [
      "div-container-s1",
      "text-1",
      "text-2",
      "text-3",
      "image-1",
      "image-2",
      "button-1",
      "button-2",
      "image-3"
    ]
  },
  {
    "stepname": "Step 2",
    "stepnum": 2,
    "elements": [
      "div-container-s2",
      "text-4",
      "text-5",
      "text-6",
      "image-4",
      "image-5",
      "image-6",
      "form-1",
      "input-1",
      "button-3",
      "dropdown-1"
    ]
  },
  {
    "stepname": "Step 3",
    "stepnum": 3,
    "elements": [
      "div-container-s3",
      "text-7",
      "text-8",
      "text-9",
      "image-7",
      "text-10",
      "text-15",
      "text-16",
      "text-17",
      "text-18",
      "image-10",
      "image-11",
      "image-12",
      "image-13",
      "image-8",
      "image-9",
      "text-11",
      "text-12",
      "text-13",
      "text-14"
    ]
  }
],

function myFunction(elementType){
//code goes here
}

myFunction('text');

//output should be 0,1,2,3 because it contains "text" 

3 个答案:

答案 0 :(得分:1)

您可以在数组上使用reduce函数,并使用includes检查字符串是否包含文本。如果是,则将index推入累加器

var a = ["text-1", "text-2", "text-3", "text-4", "div-container-s1", "image-4"];

function myFunction(elementType) {
  return a.reduce((acc, curr, index) => {
    if (curr.includes(elementType)) {
      acc.push(index)
    }
    return acc;
  }, [])
}

console.log(myFunction('text'));

答案 1 :(得分:0)

尝试下面的示例

var a=["text-1","text-2","text-3","text-4","div-container-s1", "image-4"];

function getTextIndex(arrayElement) {
  var char='';
  for(var i=0; i<arrayElement.length; i++) {
    if(arrayElement[i].search(/[^a-zA-Z]+/) == -1) { 
    if(char == '')
      char = i.toString();
    else
      char = char + ', ' + i;
    }
  }
  console.log(char)
}

getTextIndex(a[0]);

答案 2 :(得分:0)

您可以使用mapfilter。首先用map返回index,它由必需的字符串组成。如果没有该字符串,则返回-1作为值。然后只需过滤您的数组即可删除-1的所有条目。

var a = ["text-1","text-2","text-3","text-4","div-container-s1", "image-4"];

function myFunction(text) {
  return a.map((x, i) => x.includes('text') ? i : -1).filter(x => x != -1);
}

console.log(myFunction('text'));