This article mainly introduces the Array usage in Javascript. Examples of common techniques in javascript such as Array traversal, value passing, and comparison are analyzed, for more information about Array usage in Javascript, see the following example. Share it with you for your reference. The specific analysis is as follows:
The Array object in JavaScript is an Array. It is a dynamic Array first, and a super complex such as "Array, List, HashMap/Dictionary" in C # and Java.
Array
Usage:
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 kakay']; for (var I = 0; IForin traverses Array
Var arr = ['hani ', 'zhuang', 'manchu ', 'floaset']; for (var item in arr) {alert (item + '====' + arr [item]);}
Array key-value pairs
Usage
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]); }
Traverse Array key-value pairs
Forin Loop
var arr={name:'James',age:28}; for(var item in arr){ alert(item+'==='+arr[item]); }
Object. Key
var arr={name:'James',age:28}; alert(arr.name); alert(arr.age);
Pass Method 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; IExample 2:
Var code = {name: 'max ', children: [{name: 'jack', age: 20}, {name: 'Rose', age: 18}]}; alert (code. name); for (var I = 0; I
> '+ Code. children [I]. age);} // Of course, forin can also be used, but for (var item in code. children) {alert (item + '>' + code. children [item]. name + '=' + code. children [item]. age );}
Array comparison
Customize a common comparison method
function max(arr,compare){ var m=arr[0]; for(var i=1;in2; }); alert(s1);var s2=max(["aa","bbbb","ccc"],function(n1,n2){ return n1.length>n2.length; });alert(s2);
Comparison Method sort () in Javascript ()
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; II hope this article will help you design javascript programs.