javascript var array code example

Example 1: javascript array

//create an array like so:
var colors = ["red","blue","green"];

//you can loop through an array like this:
for (var i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}

Example 2: javascript array

//An array is a list of thing, you can add as many things as you want

var food = ["cake", "apple", "Ice-Cream"]

//You can use Math.Random to pick a random number
//from one to the length of the array

var Number = [Math.floor(Math.random() * food.length)];
//then we can console.log the random word from the array
console.log(logammounts[woodloot])

Example 3: how to create an array in javascript

let fruits = ['Apple', 'Banana']

console.log(fruits.length)
// 2

Example 4: array 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)

Example 5: tableau javascript

console.log(arr.0); // erreur de syntaxe