This article describes the definition and usage methods of arrays in JavaScript. Share it for your reference. The specific analysis is as follows:
Copy the code as follows:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
//【Array in Dictionary】
var arr = new Array(); //Declare a dynamic array object arr
arr[0] = "tom";
arr[1] = "jim";
arr[2] = "Ergouzi";
for (var i in arr) {
alert(i); //Output 1, 2, 3 [It is not like the C# array that outputs vale, here the output is key: dictionary style]
}
for (var i = 0; i < arr.length; i++) {
alert(arr[i]); //Output tom,jim, Ergouzi
}
*/
//【Array in Dictionary】
var dict = new Array(); //Declare an array object dict
dict["people"] = "ren"; // Dynamically add a person attribute
dict["Pointer"] = "kou"; // Dynamically add a port attribute
dict["hand"] = "shou"; // Dynamically add a hand attribute
for (var item in dict) { //Transtraight through the dict array object: This for loop is equivalent to foreach traversal in C#, and the syntax is the same, but foreach has become for
alert(item); //Output person, mouth, hand [It is not like C# array output vale, here the output is key: dictionary style]
//alert(arr[item]) //If you want to output its value, you can also write it like this, so you output it: ren ,kou ,shou
}
//Since the key obtained through for (var v in dict) has this feature, then we can use this feature to obtain another member in an object (the member of the object appears in the form of the object's key)
for (var v in document) {//Output all members of the document object
document.writeln(v);
}
alert(dict["变"]); //Output kou; Because the dict array object uses "person", "mouth", and "hand" to make the key, so here we get the value "kou" based on the "mouth" key
//Arrays also have a simplified way to declare
//【Simplified declaration form of ordinary arrays】
var str = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // This kind of array can be regarded as a special case of dict["man"] = "ren"; that is, when the key is 0, 1, 2, 3..... The value is 1 when the key is 0
for (var i = 0; i < str.length; i++) {
alert(str[i]); //Output 1,2, 3, 4, 5, 6, 7, 8, 9
}
//【Dictionary style array simplified declaration form】
var str = { "tom": 30, "jim": 28, "Ergouzi": 16 };
for (var v in str) {
alert(v); //Output tom,jim, Ergouzi
}
/*
for (var i = 0; i < str.length; i++) { //Note that dictionary-style arrays whose keys are not numbers cannot be traversed in the form of this for loop. Because str[i], where this i is an index, it is a number
alert(str[i]);
}*/
</script>
</head>
<body>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.