Array

この文書は翻訳中です。他国語のままの部分などがあるのはその為です。
是非お気軽に MDN に登録して翻訳に参加し、私たちの手助けをして下さい!

概要

JavaScript は配列を扱うことができます。配列とは順序を持つ複数のデータの集合であり、JavaScript のグローバルオブジェクトである Array は、高位の、(C言語等で云うところの)「リスト」の様な、配列のコンストラクタです。

構文

[element0, element1, ..., elementN] //配列リテラル
new Array(element0, element1, ..., elementN)
new Array(arrayLength)

引数

element0, element1, ..., elementN
数値が唯一の引数として Array コンストラクタに指定された場合以外は、配列は引数に指定された値を要素として初期化され、配列の length プロパティは引数の数に設定されます (後述)。この特殊なケースは Array コンストラクタによって JavaScript の配列を生成した場合にのみ適用され、ブラケット構文を使用する配列リテラルには適用されない点に注意してください。
arrayLength
Array コンストラクタに渡される唯一の引数(arrayLength)に 0 から 4,294,967,295( 232-1 ) までの整数値を指定する場合は、その値を要素数とする配列が作成されます。その際に範囲外の値を指定した場合には、例外: RangeError がスローされます。

説明

配列とは、トラバーサルや変異などの操作の為のいくつかの組み込みメソッドを持つ、リストの様なオブジェクトの事を言います。JavaScript の配列は、要素数も型も固定されていません。配列のサイズは常に可変である為、JavaScript の配列は密であることが保証されていません。一般に、これらは便利な特性ではありますが、固定された配列が必要であれば、Typed Array の使用を検討するのも良いでしょう。

JavaScript の配列は連想配列として使うべきではありません。連想配列には objects を使用できますが、こちらにも注意点があります。例として Lightweight JavaScript dictionaries with arbitrary keys の投稿記事をご覧ください。

配列要素へのアクセス

JavaScript の配列のインデックスは 0 から始まります。配列の最初の要素のインデックスは 0。つまり、最後の要素のインデックスは length プロパティの値より 1 小さい値になります。

var arr = ["最初の要素", "2 番目の要素"];
console.log(arr[0]);              // ログ : "最初の要素"
console.log(arr[1]);              // ログ : "2 番目の要素"
console.log(arr[arr.length - 1]); // ログ : "2 番目の要素"

toString が一つのプロパティであるように、配列における配列要素は Array オブジェクトのプロパティです。しかし、次のように配列の最初の要素にアクセスしようとすると、構文エラーがスローされる事に注意してください。

console.log(arr.0);

これは JavaScript の配列とそのプロパティに限った話ではありません。オブジェクトの、数字から始まるプロパティに対してはドット演算子を用いた参照は出来ません。そこで、ブラケット記法を用いる必要があります。例えば "3d" というプロパティを持つオブジェクトがある場合は、ドット記法ではなくブラケット記法を使用して参照しなければなりません。この類似点を、以下 2 つのコード例で示します:

var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];

try {
  console.log(years.0);
}
catch (ex) {
  console.log("ブラケット記法でのアクセス");
  console.log(years[0]);
}
try {
  renderer.3d.setTexture(model, "character.png");
} catch (ex) {
  console.log("Using bracket notation");
  renderer["3d"].setTexture(model, "character.png");
}

3d の例で、"3d" は引用符で括らなければなりません。必要は有りませんが、配列要素へのアクセスにも years[2] でなく years["2"] を使う事が出来ます。years[2] の 2 は最終的に、JavaScript エンジンが内部的に toString メソッドで型変換することで文字列にされます。これは "2" と "02" が years オブジェクトの異なる場所を指すようにするためであり、このため以下の例は true がログ出力されます:

console.log(years["2"] != years["02"]);

length と数値プロパティとの関係

JavaScript の配列の lengthプロパティと数値プロパティは関連しています。 joinsliceindexOf 等の配列のビルトインメソッドは、配列のlengthプロパティの値を考慮します。 また、pushsplice等は、配列の length プロパティも更新します。

var fruits = [];

fruits.push("banana", "apple", "peach");
console.log(fruits.length); // logs 3

有効なインデックスを持つ JavaScript の配列の現在のサイズに収まらない位置に要素を追加すると、配列はそれを収められる位置まで拡張され、length プロパティも更新されます。

fruits[3] = "mango";

console.log(fruits[3]);
console.log(fruits.length); // logs 4

length プロパティを直接設定した時も特殊な動作となります。

fruits.length = 10;

console.log(fruits);        // "undefined" で満たされている
console.log(fruits.length); // 10

これらについては length ページで更に解説します。

match の結果を利用して配列を作成

正規表現と文字列の一致から配列を作る事が出来ます。この配列にはプロパティと、マッチに関する情報を提供する要素を持ちます。 配列は RegExp.exec、 String.match、そして String.replace の戻り値です。 これらのプロパティと要素を理解するために、以下の例と表を参照して下さい。

// 1 文字の d、1 文字以上の b、1 文字の d にマッチします
// マッチした b およびその後の b を記憶します
// 大文字小文字は区別しません

var myRe = /d(b+)(d)/i;
var myArray = myRe.exec("cdbBdbsbz");

プロパティとこの一致から返される要素は以下のとおりです。

プロパティ/要素 説明
input 正規表現がマッチした、元の文字列を反映する読み取り専用プロパティです。 cdbBdbsbz
index

文字列中でマッチした場所を、0 から始まるインデックスで示す読み取り専用プロパティです。

1
[0] 最後にマッチした文字列を指定する読み取り専用の要素です。 dbBd
[1], ...[n] 正規表現に含まれる場合、括弧で囲まれたマッチした部分文字列を指定する読み取り専用の要素です。括弧で囲まれた部分文字列の数は無制限です。 [1]: bB
[2]: d

プロパティ

Array インスタンスから継承されているPropertiesについては、Array インスタンスのPropertiesを参照してください。

prototype
全てのオブジェクトにプロパティを追加することができます。
Function から継承されるプロパティ

メソッド

Array インスタンスから継承されているMethodsについては、Array インスタンスのMethodsを参照してください。
isArray JavaScript 1.8.5 が必要
配列であれば true を、配列でなければ false を返す

Array インスタンス

Array インスタンスは、Array.prototype を継承します。全てのコンストラクタと同様に、コンストラクタのプロトタイプオブジェクトを変更して、Array インスタンスの全てを変更することができます。

プロパティ

constructor
Specifies the function that creates an object's prototype.
length
Reflects the number of elements in an array.

メソッド

Mutator methods

These methods modify the array:

pop
Removes the last element from an array and returns that element.
push
Adds one or more elements to the end of an array and returns the new length of the array.
reverse
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
shift
Removes the first element from an array and returns that element.
sort
Sorts the elements of an array in place and returns the array.
splice
Adds and/or removes elements from an array.
unshift
Adds one or more elements to the front of an array and returns the new length of the array.

Accessor methods

These methods do not modify the array and return some representation of the array.

concat
Returns a new array comprised of this array joined with other array(s) and/or value(s).
join
Joins all elements of an array into a string.
slice
Extracts a section of an array and returns a new array.
toSource Non-standard
Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the Object.prototype.toSource method.
toString
Returns a string representing the array and its elements. Overrides the Object.prototype.toString method.
indexOf Requires JavaScript 1.6
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
lastIndexOf Requires JavaScript 1.6
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

Iteration methods

Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.

forEach Requires JavaScript 1.6
Calls a function for each element in the array.
every Requires JavaScript 1.6
Returns true if every element in this array satisfies the provided testing function.
some Requires JavaScript 1.6
Returns true if at least one element in this array satisfies the provided testing function.
filter Requires JavaScript 1.6
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
map Requires JavaScript 1.6
Creates a new array with the results of calling a provided function on every element in this array.
reduce Requires JavaScript 1.8
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
reduceRight Requires JavaScript 1.8
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

Array ジェネリックメソッド

文字列や他の配列のようなオブジェクト (関数の arguments など) に Array のメソッドを適用したいと考える場合があります。これにより、文字列を文字の配列として扱います (あるいは、配列ではないものを配列として扱う)。例えば、変数 str に含まれる文字がすべて英字であることをチェックするには、次のように書くでしょう:

function isLetter(character) {
  return (character >= "a" && character <= "z");
}

if (Array.prototype.every.call(str, isLetter))
  alert("The string '" + str + "' contains only letters!");

この記法はかなりむだであり、JavaScript 1.6 で汎用的な簡易表記を導入しました:

if (Array.every(isLetter, str))
  alert("The string '" + str + "' contains only letters!");

ジェネリックメソッドString でも使用できます。

これらは現在 ECMAScript 標準に含まれていません (ただしこれを実現するために、ES6 の Array.from() を使用できます)。以下は、あらゆるブラウザでこれらを可能にするためのシムです:

/*globals define*/
// Array の拡張は提供されているものと仮定 (ひとつの方法として、さらにシムを使用します)
(function () {
    'use strict';

    var i,
        // 下記の方法で array のメソッドを構築することも可能ですが、
        //   getOwnPropertyNames() メソッドはシムを適用できません:
        // Object.getOwnPropertyNames(Array).filter(function (methodName) {return typeof Array[methodName] === 'function'});
        methods = [
            'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
            'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
            'forEach', 'map', 'reduce', 'reduceRight', 'filter',
            'some', 'every', 'isArray'
        ],
        methodCount = methods.length,
        assignArrayGeneric = function (methodName) {
            var method = Array.prototype[methodName];
            Array[methodName] = function (arg1) {
                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
            };
        };

    for (i = 0; i < methodCount; i++) {
        assignArrayGeneric(methods[i]);
    }
}());

例: 配列を生成する

次の例では、空の配列「msgArray」を生成し、msgArray[0]msgArray[99] に値を設定、その後配列の要素数が 100 である事を確認しています。

var msgArray = new Array();
msgArray[0] = "Hello";
msgArray[99] = "world";

if (msgArray.length == 100) {
   print("配列の length は 100 です。");
} 

例: 2 次元配列を生成する

以下では、文字列の 2 次元配列としてチェスボードを生成しています。 最初の動きは 6,4 の 'P' を 4,4 にコピーすることでなされます。 位置 6,4 は空白にされます。

var board = 
[ ['R','N','B','Q','K','B','N','R'],
  ['P','P','P','P','P','P','P','P'],
  [' ',' ',' ',' ',' ',' ',' ',' '],
  [' ',' ',' ',' ',' ',' ',' ',' '],
  [' ',' ',' ',' ',' ',' ',' ',' '],
  [' ',' ',' ',' ',' ',' ',' ',' '],
  ['p','p','p','p','p','p','p','p'],
  ['r','n','b','q','k','b','n','r']];
print(board.join('\n') + '\n\n');

// キングの前のポーンを 2 つ前へ移動
board[4][4] = board[6][4];
board[6][4] = ' ';
print(board.join('\n'));

出力を以下に示します:

R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
 , , , , , , , 
 , , , , , , , 
 , , , , , , , 
 , , , , , , , 
p,p,p,p,p,p,p,p
r,n,b,q,k,b,n,r

R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
 , , , , , , , 
 , , , , , , , 
 , , , ,p, , , 
 , , , , , , , 
p,p,p,p, ,p,p,p
r,n,b,q,k,b,n,r

ブラウザ実装状況

機能 Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
基本サポート (有) (有) (有) (有) (有)
機能 Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
基本サポート (有) (有) (有) (有) (有)

関連情報

タグ (3)