About Arrays in JavaScript:
An array is a list of elements which is to store a large amount of element under a single name. The length of the array in JavaScript is not fixed.
=> Let's define an array with numbers stored form 1 to 5.
let number = [1, 2, 3, 4, 5];
=> You can define an array with string elements.
let animal = ["dog", "Cat", "monkey", "tiger"];
=> We can also define an array with mixed elements.
let data = [1, 2, "hello", 4];
How to access any index element in JavaScript:
For example, we want to access the second element of the data array;
we will use
data[1];
because of indexing in javascript array start from 0.
Now let's perform some operation on arrays by using build-in methods;
1. Length of the array:
'
let numbers = [1, 2, 3, 4];
numbers.length;
// 4
2. Map function to loop over the array and perform an action on each element in this case double all element and store it in the new array:
let numbers = [1, 2, 3, 4];
let doubleNumbers = numbers.map(function(num) {
return 2 * num;
});
console.log(doubleNumbers);
console.log(doubleNumbers);
// [2. 4. 6. 8]
So, in the above map function, we are performing the anonymous function which is doubling all the element and returning it to doubleNumbers.
3. Adding a new element at the end of the array (push function):
let numbers = [1, 2. 3. 4];/div>
numbers.push(5);
console.log(numbers);
// [1, 2, 3, 4, 5];
4. Remove element from the end of Array (pop function):
let numbers = [1, 2, 3, 4];
numbers.pop();
console.log(numbers);
// [1, 2, 3]
No comments:
Post a Comment