查找数组的索引位置[重复]

var cars = ["BMW", "BENZ", "LAMB", "AUDI"];
var abc = cars.indexOf("BMW");
document.getElementById("demo").innerHTML = abc;
<p id="demo"></p>

这是显示位置的代码,但是我要相反,即如果我输入一个位置,它应该显示数组值。如何获得?

评论
  • kautem
    kautem 回复

    Use array[index]

    var index = 0;
    var cars = ["BMW", "BENZ", "LAMB", "AUDI"];
    var abc = cars[index];
    document.getElementById("demo").innerHTML = abc;
    <p id="demo"></p>
  • nerror
    nerror 回复

    干得好

    const cars = ["BMW", "BENZ", "LAMB", "AUDI"];
    let indexIWant = 0;
    document.getElementById("demo").innerText = cars[indexIWant];
    <p id="demo"></p>