Examples of Array Usage Analysis and array instance analysis in Javascript
This example describes how to use Array in Javascript. 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; I <arr. length; I ++) {alert (arr [I]);}
Forin 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;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 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;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 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;i<arr.length;i++){ alert(arr[i].name);//Tom,Rose,Bob }
I hope this article will help you design javascript programs.