Monday, December 16, 2013

Array in javascript - Basics

Declare an Array

var arr = new Array(); // Declaring an empty array.

var arr = [5,'sky blue','test']; // Simple array with custom values and default keys.
Structure: arr( [0] => 5,
                       [1] => sky blue,
                       [2] => test
                     );

var arr = [ {'id':23}, {'name':'green'}, {'category':'color'} ]; // Simple array with custom values and custom keys.
Structure: arr( [id]  => 23,
                       [name] => green,
                       [category] => color
                     );

var arr=[ {'id':23,'name':'green','category':'color'}, {'id':24,'name':'mango','category':'fruit'}, {'id':25,'name':'rose','category':'flower'} ]; // Multidimensional array with custom values and custom keys.


Access an Array

// Now consider arr is an array, which had we already created.

console.log(arr); // Display array in JavaScript console.

arr['new']='something'; // Add a new value with specific key.

arr.push('somemore'); // Add a new value with out specific key.

arr.pop(); // Remove last element from array.

arr.shift(); // Remove first element from array.


For Each in Array

<script type='text/javascript' src='js/jquery.js'></script> // JQuery need for use $.each function
var arr = [5,10,15];
$.each(arr,function(key,value){
console.log(key+' : '+value);
});
//Out put:
0 : 5
1 : 10
2 : 15


Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...