Collection array
2 Ways to create arrays
var fruits = [];
var friuits = new Array ();
Traverse
Fruits.foreach (function (item, index, array) {
Console.log (item, index);
});
Apple 0
Banana 1
Basic operations
| action |
code |
return value |
| add element to end of array |
fruits.push (' Orange ') |
array length |
| add element To the head of the array |
fruits.unshift (' Strawberry ') |
array length |
| delete header element |
fruits.shift (); |
Header Element |
| delete trailing elements |
fruits.pop (); |
trailing element |
| to find out the index of an element in an array |
fruits.indexof (' Banana '); |
Subscript |
| delete an element by index |
fruits.splice (index, 1); |
deleted elements |
| copy array |
var shallowcopy = Fruits.slice (0,length); |
returns a new array of elements within the specified range |
| generate array |
array.from () |
Array.from () method creates a new array instance from a similar array or an iterator object. |
Example of deleting elements based on an index
/* Splice (Start:number, Deletecount:number, ... items:t[]): t[]; */
var fruits = ["Apple", "B", "C", "D"];
Console.log ("Array is:");
Fruits.foreach (function (item, index, array) {
Console.log (item, index);
});
var index = fruits.indexof ("B");
Fruits.splice (index,1);
Console.log ("Array is:");
Fruits.foreach (function (item, index, array) {
Console.log (item, index);
});
Array.from () Use example
var fruits = ["Apple", "B", "C", "D"];
var f = array.from (fruits);
F.foreach (function (item, index, array) {
Console.log (item, index);
});
Apple 0
B 1
C 2
D 3
var f = array.from ("Hello");
F.foreach (function (item, index, array) {
Console.log (item, index);
});
H
E
L
L
O
Array.from () can also be used for Set,map
Setmap
JavaScript Advanced (not finished)