配列の生成

(1) var myArray = new Array(); myArray[0] = "Alice"; myArray[1] = "Fred"; (2) var myArray = new Array ("Alice", "Fred", "Jean"); (3) var myArray = ["Alice", "Fred", "Jean"]; (応用) lengthプロパティを使って、要素を追加する。 myArray[myArray.length] = "Steve";

多次元配列

(1) var array1 = new Array(10,20,30,40); var array2 = new Array(100,200,300,400); var array3 = new Array(1000,2000,3000,4000); var myArray = new Array(array1, array2, array3); (2) var myArray = [[10,20,30,40], [100,200,300,400], [1000,2000,3000,4000]];

オブジェクト配列

(オブジェクト) function showAll() { alert("Employee " + this.name + " is " + this.age + " years old."); } function coworker(name, age) { this.name = name; this.age = age; this.show = showAll; } オブジェクトを配列に格納する方法は3種類。 (1) var employeeDB = new Array(); employeeDB[employeeDB.length] = new coworker("Alice", 23); employeeDB[employeeDB.length] = new coworker("Fred", 32); employeeDB[employeeDB.length] = new coworker("Jean", 28); employeeDB[employeeDB.length] = new coworker("Steve", 24); (2) var employeeDB = new Array(); employeeDB[employeeDB.length] = {name:"Alice", age:23, show:showAll}; employeeDB[employeeDB.length] = {name:"Fred", age:32, show:showAll}; employeeDB[employeeDB.length] = {name:"Jean", age:28, show:showAll}; employeeDB[employeeDB.length] = {name:"Steve", age:24, show:showAll}; (3) var employeeDB = [{name:"Alice", age:23, show:showAll}, {name:"Fred", age:32, show:showAll}, {name:"Jean", age:28, show:showAll}, {name:"Steve", age:24, show:showAll}]; 配列を使って、ある年齢の範囲のデータを検索。 var result = new Array(); for (var i = 0; i < employeeDB.length; i++) { // 20歳から30歳の範囲を検索 if (employeeDB[i].age >= 20 && employeeDB[i].age <= 30) { result = result.concat(employeeDB[i].name); } }

連想配列

上記オブジェクト配列から、連想配列(ハッシュテーブル)を作成。 for (var i = 0; i < employeeDB.length; i++) { employeeDB[employeeDB[i].name] = employeeDB[i]; } 連想配列からの参照方法は var age = employeeDB["Alice"].age;

要素の削除

置換メソッドspliceに、置換文字列を指定せずに呼び出す。
配列の1番目から3番目までの要素を削除する。

myArray = new Array(0,1,2,3,4,5,6); p1 = 1; p3 = 3; myArray.splice(p1,p3);