The push and pop functions let you add and remove items to the end of an array, respectively:
var nums = [ 1, 1, 2, 3, 5, 8 ];
nums.push(13);
console.log(nums);
nums.pop();
console.log(nums);
The code above generates the following result.
To insert or delete items from the front of an array, use unshift or shift , respectively:
var nums = [ 1, 2, 3, 5, 8 ];
nums.unshift(1);
console.log(nums);
nums.shift();
console.log(nums);
The array function join returns a string from the array:
var nums = [ 1, 1, 2, 3, 5, 8 ];
var s = nums.join(", ");
console.log(s);
The code above generates the following result.
You can sort arrays using the sort function, which can be used with the built-in sorting function:
var nums = [ 3, 1, 8, 5, 2, 1];
nums.sort();
console.log(nums);
The code above generates the following result.
We can provide your own sorting function as a parameter:
var names = [ 'CSS', 'HTML', 'Java', 'SQL', 'CSS3', 'HTML5'];
names.sort();/* w w w . j a va 2 s . co m*/
console.log(names);
names.sort(function (a, b) {
var a1 = a.toLowerCase(), b1 = b.toLowerCase();
if (a1 < b1) return 1;
if (a1 > b1) return -1;
return 0;
});
console.log(names);
The code above generates the following result.
To iterate over items in arrays, we can use the for loop or forEach function
[ 'CSS', 'HTML', 'CSS3', 'HTML5', 'Javascript', 'SQL'].forEach( function (value) {
console.log(value);
});
The code above generates the following result.