how to insert an element into an array in javascript
How to insert an element into an array in javascript
To create an array in javascript you have to use a variable to store the array data
// first use a variable to store array value
var Arr;
// This will intialize the array value
// Now create the array obj with the help of new Keyword
Arr = new Array();
// Now add the elements in the Array using the predefined array method
// first to add element we will use the push() method
//Syntax: push()
// Inorder to add elements you will have to follow these steps:
Arr.push();
// Now you can add elements in the array with .push() method
//Just mention the element you want to insert
//for example
Arr.push('apple');
//Now this adds the apple into the array
// How will the array look like
//Array[apple]
//length = 1
// index of apple would be 0
// You can add multiple elements on the go or Add single element one by one as metioned Above
// How to add elements on one Go or in one line
Arr.push('kiwi',grapes','orange');
// This Statement will add multiple element in the ARRAY Arr
//Now Are you wondering what will be the output
// so don't wait for me try this out in the console
// Output
// Array[apple,kiwi,grapes,orange]
// the element Apple comes from the above line
// And rest elm were added later
// So the length now incremented to the value 4
// And the index of the elm would be
//Apple:0
//kiwi:1
//grapes:2
//Orange:3
NOTE:: Push() method always add the element at the end of the array. It returns the array of modified
length.
Comments
Post a Comment