JavaScript 数组 indexOf() 方法无效
JavaScript Array indexOf() Method not working
我正在尝试在数组中查找一个项目。我的变量 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");
}
}
万一找到该项目,我不想将其添加到数组中。
你得到 -1 是因为当你写 var sortiment = [];
时,这意味着当你 运行 .IndexOf(something)
时在数组中找不到它
这是一个参考:http://www.w3schools.com/jsref/jsref_indexof_array.asp
function filterOptions(eigenschaft, filter){
inhalt = filter + " = " + eigenschaft;
console.log(inhalt);
console.log(sortiment[0]);
switch(filter) {
case "sortiment":
sortiment.push(inhalt);//remove [ ]
break;
case "geschmack":
geschmack.push(inhalt);
break;
case "kategorie":
kategorie.push(inhalt);
break;
default:
console.log("FAIL");
}
a = sortiment.indexOf(inhalt); //look for index after .push
console.log(a);
}
您正在将包含单个元素(字符串)的(内部)数组推入(外部)数组,但随后您正在从外部数组中搜索字符串的索引。那是行不通的。换句话说,问题很可能是这样的:
geschmack.push([inhalt]);
为什么会有那些方括号?你可能想要这个:
geschmack.push(inhalt);
如果您想将其可视化,您的数组最终将看起来像这样:
[ ["filter1=eigenschaft1"], ["filter2=eigenschaft2"] ]
但您不是在搜索 ["filter1=eigenschaft1"]
;您正在搜索 "filter1=eigenschaft1"
,因此它当然找不到。或者,您可以更改此行:
a = sortiment.indexOf([inhalt]);
但老实说,这整件事似乎已经有点令人费解了。
我正在尝试在数组中查找一个项目。我的变量 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");
}
}
万一找到该项目,我不想将其添加到数组中。
你得到 -1 是因为当你写 var sortiment = [];
时,这意味着当你 运行 .IndexOf(something)
这是一个参考:http://www.w3schools.com/jsref/jsref_indexof_array.asp
function filterOptions(eigenschaft, filter){
inhalt = filter + " = " + eigenschaft;
console.log(inhalt);
console.log(sortiment[0]);
switch(filter) {
case "sortiment":
sortiment.push(inhalt);//remove [ ]
break;
case "geschmack":
geschmack.push(inhalt);
break;
case "kategorie":
kategorie.push(inhalt);
break;
default:
console.log("FAIL");
}
a = sortiment.indexOf(inhalt); //look for index after .push
console.log(a);
}
您正在将包含单个元素(字符串)的(内部)数组推入(外部)数组,但随后您正在从外部数组中搜索字符串的索引。那是行不通的。换句话说,问题很可能是这样的:
geschmack.push([inhalt]);
为什么会有那些方括号?你可能想要这个:
geschmack.push(inhalt);
如果您想将其可视化,您的数组最终将看起来像这样:
[ ["filter1=eigenschaft1"], ["filter2=eigenschaft2"] ]
但您不是在搜索 ["filter1=eigenschaft1"]
;您正在搜索 "filter1=eigenschaft1"
,因此它当然找不到。或者,您可以更改此行:
a = sortiment.indexOf([inhalt]);
但老实说,这整件事似乎已经有点令人费解了。