Change Elements

Array elements are accessed using their index number. Array indexes start with 0. The first array element is [0], the second array element is [1], the third is [2] ... You can change any element, using it's index number, which you can find with indexOf:

HTML file: Displayed by browser:
<body>
<h4>Original array:</h4>
<p id="demo"></p>
<hr />
<h4>Find the index of Orange:</h4>
<button onclick="myIndex()">Find Index</button>
<p id="demo1"></p>
<hr />
<h4>Swap Orange with Kiwi, using index access:</h4>
<button onclick="mySwap()">Swap it</button>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myIndex() {
    document.getElementById("demo1").innerHTML = fruits.indexOf("Orange");
}
function mySwap() {
    fruits[1] = "Kiwi";   // Swap Orange with Kiwi
    document.getElementById("demo2").innerHTML = fruits;
}
</script>
</body>

Original array:


Find the index of Orange:


Swap Orange with Kiwi, using index access:


BackTable of ContentsNext