我有以下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
的字符串数。
答案 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);