Adding elements to an array in JavaScript
JavaScript arrays are objects which can be initialized using a syntax of
["", ...] Parentheses with a number of elements ie
var oddNumbers = [2, 4, 6]
or var numbers = ["one", "two", "three"]
["", ...] Parentheses with a number of elements ie
var oddNumbers = [2, 4, 6]
or var numbers = ["one", "two", "three"]
Or the global Array constructor using syntax ie
var integer = new Array(length = 2)
console.log(integer) // [null, null]
where length species blank filler value by default the element is null and you can't iterate them to change the fill value you can call the fill method of an array ie
integer.fill(0)
console.log(integer) // [0, 0]
You can append an element to any of the arrays declared above using push , prepend using unshift, assign using manual assigning
Manual assignment
Simplest way is by simply assigning a new element
oddNumbers['index'] = "Number"
ie oddNumbers[3] = 8;
console.log(oddNumbers) // [2, 4, 6, 8]
oddNumbers['index'] = "Number"
ie oddNumbers[3] = 8;
console.log(oddNumbers) // [2, 4, 6, 8]
Push
Its a method for appending elements to an array is
oddNumbers.push(0)
console.log(oddNumbers) // [0, 2, 4, 6, 8]
Unshift
Its a method for prepending elements to an array
oddNumbers.unshift(10)
console.log(oddNumbers) // [0, 2, 4, 6, 8, 10]
Comments
Post a Comment