我正在尝试在数组中查找一个项目。我的变量 a
只得到 -1,因此在我的数组中找不到该项目,但该项目肯定在数组中。
var sortiment = [];
var geschmack = [];
var kategorie = [];
function filterOptions(eigenschaft, filter){
inhalt = filter + " = " + eigenschaft;
console.log(inhalt);
console.log(sortiment[0]);
a = sortiment.indexOf(inhalt);
console.log(a);
switch(filter) {
case "sortiment":
sortiment.push([inhalt]);
break;
case "geschmack":
geschmack.push([inhalt]);
break;
case "kategorie":
kategorie.push([inhalt]);
break;
default:
console.log("FAIL");
}
}
如果找到该项目,我不想将其添加到数组中。
最佳答案
您将包含单个元素(字符串)的(内部)数组插入(外部)数组,但随后您正在从外部数组中搜索字符串的索引。那是行不通的。换句话说,问题很可能是这样的:
geschmack.push([inhalt]);
为什么会有那些方括号?您可能想要这个:
geschmack.push(inhalt);
如果你想可视化这一点,你的数组最终将看起来像这样:
[ ["filter1=eigenschaft1"], ["filter2=eigenschaft2"] ]
但是您不是在搜索["filter1=eigenschaft1"]
;您正在搜索 "filter1=eigenschaft1"
,所以它当然找不到它。或者,您可以更改此行:
a = sortiment.indexOf([inhalt]);
但说实话,整件事看起来已经有点复杂了。
关于JavaScript 数组indexOf()方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31996210/