what is a javascript list code example
Example 1: list javascript
//Creating a list
var fruits = ["Apple", "Banana", "Cherry"];
//Creating an empty list
var books = [];
//Getting element of list
//Lists are ordered using indexes
//The first element in an list has an index of 0,
//the second an index of 1,
//the third an index of 2,
//and so on.
console.log(fruits[0]) //This prints the first element
//in the list fruits, which in this case is "Apple"
//Adding to lists
fruits.push("Orange") //This will add orange to the end of the list "fruits"
fruits[1]="Blueberry" //The second element will be changed to Blueberry
//Removing from lists
fruits.splice(0, 1) //This will remove the first element,
//in this case Apple, from the list
fruits.splice(0, 2) //Will remove first and second element
//Splice goes from index of first argument to index of second argument (excluding second argument)
Example 2: list javascript
//Their are no lists in javascript, they are called arays,wich are basically the same thing
var fruits = ['Apple', 'Banana'];
console.log(fruits.length);
// 2
var first = fruits[0];
// Apple
var last = fruits[fruits.length - 1];
// Banana
fruits.forEach(function(item, index, array) {
console.log(item, index);
});
// Apple 0
// Banana 1
var newLength = fruits.push('Orange');
// ["Apple", "Banana", "Orange"]
var last = fruits.pop(); // deletes orange
// ["Apple", "Banana"];
var first = fruits.shift(); // supprime Apple (au début)
// ["Banana"];
var newLength = fruits.unshift('Strawberry') // adds to the start
// ["Strawberry", "Banana"];
fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]
var pos = fruits.indexOf('Banana');
// 1
var removedItem = fruits.splice(pos, 1); // deletes on element at the position pos
//removes one element at the position pos
// ["Strawberry", "Mango"]
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
console.log(vegetables);
// ["Cabbage", "Turnip", "Radish", "Carrot"]
var pos = 1, n = 2;
var removedItems = vegetables.splice(pos, n);
// n defines the number of element to delete starting from pos
console.log(vegetables);
// ["Cabbage", "Carrot"]
console.log(removedItems);
// ["Turnip", "Radish"] (splice returns list of deleted objects)