Arrays
Array elements are numbered, starting with zero. So the first is 0. second is 1…
There are ways to defined an array.
var array = new Array;
array = [];
or we can just input the value to define the array.
var array = [0, 1, "a", "b", false]
Let’s use the array below.
var names = ['John', 'Mark', 'Alan', 'Faye'];
var years =new Array (1969, 1948, 1989, 1990);
console.log(names); //result (4) ["John", "Mark", "Alan", "Faye"]
console.log(names.length); //result 4
console.log(names[2]); //result Alan.
Add data into array
names[1] = 'Chris';
names[5] = 'Lucus';
console.log(names);//result (6) ["John", "Chris", "Alan", "Faye", empty, "Lucus"]
names[names.length] = 'Alina'; // It will always add data in the end of the array.
You can insert different type of data into array
var John = ['John', 'Li', 1991, 'designer', false]
push data value into the end of array
John.push('blue');
console.log(John);// reuslt: (6) ["John", "Li", 1991, "designer", false, "blue"]
unshift is input the value at the begin of array
John.unshift('Mr.');
console.log(John);// result: (7) ["Mr.", "John", "Li", 1991, "designer", false, "blue"]
shift is delete the first value of array
John.shift();
console.log(John);// result: (6) ["John", "Li", 1991, "designer", false, "blue"]
pop is delete the last value of array
John.pop();
console.log(John);// result: (5) ["John", "Li", 1991, "designer", false]
Once there is no sepecific value in array (23), it will return -1 which means there is no value ‘23’
console.log(John.indexOf(23)); // result: -1.
We can use this way to define the if else statement. If a == b is true, then execute C; if a == b is false, then execute D. (Note: == compare value only; === compare value and type.)
var a === b ? " C " : " D "
Here, if John is not a designer, it will return ‘John is NOT a designer’ ; if John is a designer, it will return ‘John IS a designer’.
var isDesigner = John.indexOf('designer') === -1 ? 'John is NOT a designer' : 'John IS a designer';
console.log(isDesigner); //reuslt: John IS a designer
console.log(John.indexOf('designer')); // result: 3.