如何将数组与字符串进行比较并为每个结果增加变量

时间:2016-07-30 23:54:46

标签: javascript arrays

我有以下Javascript代码:

  var test = ['hello', 'my', 'name'];

  for (var i = 0; i < data.length; i++) {
    if (test === "name") {
      //In the array!
      ct = "found";
    } else {
      ct = "not found";
    }
  };

在这里,我尝试在data中循环显示数组,让我们说100个结果,然后确定var test是否包含&#39; name&#的数组字符串39 ;.

我已经运行了这个并在控制台日志中打印出ct的结果,并且每次打印出ct时都没有找到&#39;

这一点是要找出我在数组中定义test的字符串数。

1 个答案:

答案 0 :(得分:1)

如果您只想查找项目是否存在,那么您可以使用

var test = ["hello","my","name"];
var element = "hello";
var index = test.indexOf(element);
if(index != -1){
     //it exists 
     console.log(element + " exists at index " + index);
}else{
    //it doesn't
    console.log(element + " doesn't exist in array");
}

如果您想要像开始那样循环遍历数组:

  var test = ['hello', 'my', 'name'];
  var name = "hello";
  var ct = null;
  for (var i = 0; i < data.length; i++) {
    if (test[i] === name ) {
      //In the array!
      ct = "found";
      break; // if next element is not name, so if you found break
    } else {
      ct = "not found";
    }
  };
  console.log(ct);