0

JavaScript でオブジェクトの配列を作成しようとしています。どういうわけか、探している答えがどこにも見つかりませんでした。はい、質問を検索しました。

したがって、従来のオブジェクトには明らかに次のようなプロパティがあります。

オブジェクトであるアイテム

item = new Object();

プロパティとメソッドで

item.name = "sword"; // "sword" being the string name of the object
item.buy = buy; //buy being a function to add said item

それは素晴らしいことです。私はそれを理解しています。

私も配列を取得します。

私の質問は、これらのオブジェクトを 20 と言いたい場合、多くのオブジェクトを作成する代わりに、どうすればそれらを配列に作成できるかということです

たとえば、私はこれができることを知っています。

item1 = new Object();
item1.name = "sword";
item1.buy = buy;

item2 = new Object();
item2.name = "shield";
item2.buy = buy;

しかし、私はこのようなことをしたいと思います

item = new Array();
item[0].name = "sword";
item[0].buy = buy;

item[1].name = "shield";
item[1].buy = buy;

明らかかもしれませんが、ここで何が問題なのかわかりません。

電話しようとすると

item[0].buy(); 

「Uncaught TypeError: Object 0 has no method 'buy'」というエラーが発生し、item[0].name が未定義です。

私は何を間違っていますか、どうすればこれに対処できますか?

4

7 に答える 7

4

私の推測では、あなたが望むのはオブジェクトの配列です:

var item = new Array();
item[0] = {};
item[0].name = "sword";
item[0].buy = function() { return this.name };
item[0].buy();
// -> "sword"
于 2013-10-28T00:22:43.470 に答える
2
// create a new array
var items = [];

// You can push objects onto the array as literals like this
items.push({
 name: "sword",
 buy: buy
});

// Or you can create the new object as you're doing currently    
var item = new Object();
item.name = "shield";
item.buy = buy;

// And push it onto the array as before
items.push(item);

// Now you can access each object by it's index in the array 
items[0].buy();
console.log(items[1].name); // "shield"
于 2013-10-28T00:22:39.187 に答える
0

0配列のインデックスにオブジェクトを作成していないためbuy、関数にする必要があります

item = new Array();
// create an object at 0/first index of array which is equivalent of new Object
item[0] = {};
// create property 'name' and assign value ("sword") to it
item[0].name = "sword";
// create another property and assign a function as it's value
// so buy is a method of the first object that is in in the item array
item[0].buy = function(){
    return 'buy called';
};
// call 'buy' method from the first object of item array
console.log(item[0].buy());
于 2013-10-28T00:23:28.340 に答える
0

items.push(item1) を介して配列にアイテムを追加しなかったかのように見えます

item1 = {};
item2 = {};

item1.name = "a";
item2.name = "b";

var buy = function() { console.log('buying... '+this.name); };

item1.buy = buy;
item2.buy = buy;

var items = [];

items.push(item1);
items.push(item2);
items[0].buy();
于 2013-10-28T00:29:59.260 に答える