我在W3schools上找到了这个indexOf-Tryit,并决定尝试将其修改为一个函数,该函数查找“ Apple”的每个实例的索引值并将其输出到一个段落。我无法使其正常工作,这使我发疯。
我尝试使用具有许多不同变体的for和while循环。
function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];
for (i=0; i < fruits.length; i++) {
if (fruits[i] = fruits.indexOf("Apple")) {
document.getElementById("demo").innerHTML += fruits[i];
} else {
document.getElementById("demo").innerHTML += "x"}
}
}
我希望该段落显示“ 0x2x45xx8x10”或“ 0245810”,而不进行else操作。相反,我得到的是“ x224458881010”。
答案 0 :(得分:1)
问题是if (fruits[i] = fruits.indexOf("Apple"))
,您正在更改水果的价值[i]。此外,您已经可以遍历数组,因此可以直接比较该值并使用索引。
function myFunction() {
var fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];
for (i=0; i < fruits.length; i++) {
if (fruits[i] === "Apple") {
document.getElementById("demo").innerHTML += i;
} else {
document.getElementById("demo").innerHTML += "x"}
}
}
myFunction()
<div id='demo'>
</div>
答案 1 :(得分:0)
另一种方法是将字符串值map
与索引值匹配。如果它们不匹配,则设置一个伪造的值。然后使用filter
删除所有不匹配的值。
传递要搜索的数组以及要查找的值可使该函数更可重用。并且不返回字符串允许该函数更加灵活。用.join(',')
function findIndexesOf(arr, value) {
return arr.map((e, i) => e == value ? i : null).filter( e => e != null)
}
let fruits = ["Apple", "Orange", "Apple", "Mango", "Apple", "Apple", "Tahiti", "Mango", "Apple", "Mango", "Apple"];
let appleIndexs = findIndexesOf(fruits, "Apple")
console.log("Apples:", appleIndexs.join(','))
console.log(appleIndexs)
let mangoIndexs = findIndexesOf(fruits, "Mango")
console.log(mangoIndexs)