This example describes the array usage in JavaScript. Share to everyone for your reference. The specific analysis is as follows:
The array objects in JavaScript are arrays, first a dynamic array, and a super complex like C #, Java "arrays, lists, hashmap/dictionary", and so on.
Array arrays
How to use:
Example 1:
var citys = new Array ();
Create an Array object without initializing the length, dynamic
citys[0] = ' Shanghai ';
Citys[1] = ' Beijing ';
CITYS[2] = ' Shenzhen ';
for (var i=0; i< citys.length; i++) {
alert (citys[i));
Example 2 (recommended):
var arr=[10,true, ' Wow ka ka '];
for (Var i=0;i<arr.length;i++) {
alert (arr[i]);
}
Forin Traverse Array Array
var arr=[' Hani ', ' Zhuang ', ' Manchu ', ' floating clan '];
For (var item in arr) {
alert (item+ ' = = ' +arr[item]);
}
Array key value pairs
How to use
For example:
var arr=new Array ();
arr["name"]= ' Jack ';
arr["Age"]=28;
arr["Gender"]= ' fale ';
arr["height"]=180;
For (var item in arr) {
alert (item+ ' = = ' +arr[item]);
}
Traversal array key value pairs
Forin Cycle
var arr={name: ' James ', age:28};
For (var item in arr) {
alert (item+ ' = = ' +arr[item]);
}
Through the object. Key
var arr={name: ' James ', age:28};
alert (arr.name);
alert (arr.age);
method to pass a value
function F1 (s) {
alert (s.name);
alert (s.age);
}
F1 ({name: ' Rose ', age:20});
Special guy.
Example 1:
var arr=[{name: ' James ', age:19},{name: ' Rose ', age:18},{name: ' Max ', age:20}];
for (Var i=0;i<arr.length;i++) {
alert (arr[i].name+ ' = = = ' +arr[i].age);
}
Example 2:
var code={name: ' Max ', Children:[{name: ' Jack ', Age:20},{name: ' Rose ', Age:18}]};
alert (code.name);
for (Var i=0;i<code.children.length;i++) {
alert (code.children[i].name+ ' >> ' +code.children[i].age);
}
Of course Forin also can, but trouble for
(Var item in Code.children) {
alert (item+ ' >> ' +code.children[item].name+ ' = = = ' + code.children[item].age);
}
Array comparison
Customizing a generic comparison method
function Max (arr,compare) {
var m=arr[0];
for (Var i=1;i<arr.length;i++) {
if (compare (Arr[i],m)) {
m=arr[i];
}
}
return m;
}
var S1=max ([12,32,33,100,8],function (N1,N2) {return
n1>n2;
});
alert (s1);
var s2=max (["AA", "BBBB", "CCC"],function (N1,N2) {return
n1.length>n2.length;
});
alert (S2);
Comparison method in JavaScript sort ()
Example 1:
var arr=[23,12,56,200,45];
Arr.sort (function (n1,n2) {return
n1>n2;
});
Alert (arr);
var arrstr=["AA", "BBB", "CCCC"];
Arrstr.sort (function (n1,n2) {return
n1.length>n2.length;
});
alert (ARRSTR);
Example 2:
var arr=[{name: ' Bob ', age:100},{name: ' Tom ', age:23},{name: ' Rose ', age:78}];
Arr.sort (function (n1,n2) {return
n1.age>n2.age;
});
for (Var i=0;i<arr.length;i++) {
alert (arr[i].name);//tom,rose,bob
}
I hope this article will help you with your JavaScript programming.