Javascript Array add Items to Array

Description

Javascript Array add Items to Array


let myArray = [];

myArray[myArray.length] = "Hello";
myArray[myArray.length] = "World";

console.log( myArray.length);    // 2

console.log(myArray);//  w  w w . j  av a2s .  com

myArray[9] = "I'm way out there!";

console.log( myArray.length);    

console.log(myArray);

myArray.push("Another Item", "yet another item", true, 213);

console.log( myArray.length);    

console.log(myArray);
let persons = ["HTML", "John", "CSS"];

// Append a single value to persons array
persons.push("Peter");

console.log(persons);//ww  w.ja  va  2 s. c  om
// Prints: ["HTML", "John", "CSS", "Peter"]

// Append multiple values to persons array
persons.push("Rohn", "Java");

console.log(persons);
// Prints: ["HTML", "John", "CSS", "Peter", "Rohn", "Java"]

// Loop through persons array and display all the values
for(let i = 0; i < persons.length; i++){
    console.log("<p>" + persons[i] + "</p>");
}



PreviousNext

Related