js 数组定义
国外网站搞下来的一些关于js数组操作实现 ,本教程主要是定义这方面的。
var arr = new Array ();
var arr = new Array ([length]);
var arr = [element1, element2, ..., elementN];
// In both cases the arr variable is an array that has three element: A, B, C
var arr = new Array ("A", "B", "C");
// or
var arr = ["A", "B", "C"];
// you can access the elements of the array by zero-based indices
var firstItem = arr[0]; // "A"
var thirdItem = arr[2]; // "C"
// you can get the length of the array by the length property
var len = arr.length; // 3
实例二
var arr1 = new Array ("A", "B", "C");
var arr2 = new Array (1, 2, 3);
var multiArr = new Array (arr1, arr2);
// or
var multiArr = [arr1, arr2];
// or
var multiArr = [["A", "B", "C"], [1, 2, 3]];
// you can access the elements of the array by zero-based indices
var firstRow = multiArr[0]; // same as arr1
var secondRowFirstCell = multiArr[1][0]; // 1
三
var arr = ["A", "B", "C"];
// display the elements of the array (ABC)
for (var i = 0; i < arr.length; i++) {
document.write (arr[i]);
}
// iterating with the for in statement, i will be 0, 1, 2.
// The output will be ABC
for (var i in arr) {
document.write (arr[i]);
}
四
// First we must create an array:
var arr = [];
// Add elements at the first position:
arr[0] = "A";
// Add elements at the second position:
arr[1] = "B";
// Adding an element to the end of the array:
arr.push ("C");
// Now the arr variable is an array that have three elements: A,B,C.
五
var arr1 = ["A", "B", "C"];
var arr2 = [1, 2, 3];
// Concat the arrays:
var newArr = arr1.concat (arr2);
六
var arr = ["A", "B", "C"];
document.write (arr); // output: A,B,C
arr.splice (1, 1);
document.write ("
");
document.write (arr); // output: A,C
七
var arr = {};
// You can add elements to an associative array in two different ways:
arr["name"] = "John";
arr["location"] = "Utah";
// second way
arr.age = 13;
// you can access the elements of this array by string indices
var loc = arr["location"]; // "Utah"
// or like a member
var loc = arr.location; // "Utah"
// you cannot get the length of the array via the length property,
// it contains an invalid value
var len = arr.length; // len will
八
var arr = {};
arr["name"] = "John";
arr["location"] = "Utah";
arr["age"] = 13;
// iterating with the for in statement, i will be 'name', 'location', 'age'.
// The output will be JohnUtah13
for (var i in arr) {
document.write (arr[i]);
}
九
var arr = {};
arr["name"] = "John";
arr["location"] = "Utah";
arr["age"] = 13;
// display the initial contents of the array, output: JohnUtah13
for (var i in arr) {
document.write (arr[i]);
}
delete arr.location; // delete the location property from the array
document.write ("
");
// display the current contents of the array, output: John13
for (var i in arr) {
document.write (arr[i]);
}