アイテムごとに 3 つのデータを持つ色構造を構築しようとしています。たとえば、赤には x と y があり、青には x と y があります。したがって、3 つのデータは次のようになります。color, x, y
色に基づいて x と y を読みやすくするには、どのような構造が必要ですか。私は通常そうしますpush(color, x, y)
が、ループする必要なく色ですばやく検索する必要があるため、ここでは機能しません。ここで必要な構造と、それを設定して取得する方法。
アイテムごとに 3 つのデータを持つ色構造を構築しようとしています。たとえば、赤には x と y があり、青には x と y があります。したがって、3 つのデータは次のようになります。color, x, y
色に基づいて x と y を読みやすくするには、どのような構造が必要ですか。私は通常そうしますpush(color, x, y)
が、ループする必要なく色ですばやく検索する必要があるため、ここでは機能しません。ここで必要な構造と、それを設定して取得する方法。
単純なオブジェクト (ハッシュ) はどうですか?
// Initial creation
var colors = {
blue: { x: 897, y: 98 },
red: { x: 43, y: 1334 },
yellow: { y: 12 }
}
// Adding new element to existing object
colors['green'] = { x: 19 };
// Accessing them
console.log(colors.blue.x);
console.log(colors.yellow.y);
// Accessing them with name in var
var needed = 'green';
console.log(colors[needed].x);
console.log(colors[needed]['x']);
それとも私はあなたを間違って理解しましたか?
辞書のようなものをお探しですか?!?
var colorArray = {};
colorArray["red"] = {
x: 100,
y: 200
};
colorArray["blue"] = {
x: 222,
y: 200
};
alert(colorArray["red"].x);
または、配列にも色が必要な場合
var colors = {
blue: { color:"blue", x: 100, y: 200 },
red: { color:"red", x: 50, y: 300 },
yellow: { color:"yellow", x: 30 y: 700 }
}
文字列「定数」を使用することもできます。
var RED = "red";
var colors = {};
colors[RED] = { color: RED, x: 100, y: 200 };
...
var colors = {
red : { x : 42, y : 7 },
blue : { x : .., y : .. },
...
};
alert(colors.red.x);
var colors = [
{color: 'blue', x: 897, y: 98 },
{color: 'red', x: 25, y: 1334 },
{color: 'yellow', x: 50, y: 12 }
]
for(var i in colors) {
console.log(colors[i].color);
console.log(colors[i].x);
console.log(colors[i].y);
}
// To insert into colors
colors.push({color: 'pink', x: 150, y: 200});
または、このような構造がある場合
var colors = [
['red', 837, 98],
['blue', 25, 144],
['yellow', 50, 12]
];
それから
for(var i in colors) {
console.log(colors[i][0]); // output: red, yellow ...
console.log(colors[i][1]); // output: 837, 25 ..
console.log(colors[i][2]); // output: 98, 144 ..
}
and to insert into colors for this structure
colors.push(['pink', 150, 200])
また
var colors = {
blue: { x: 58, y: 100 },
red: { x: 43, y: 1334 },
yellow: {x: 254, y: 12 }
}
それから
for(var i in colors) {
console.log(colors[i].blue.x);
console.log(colors[i].blue.y);
// or
console.log(colors[i]['blue'].x);
// or like
console.log(colors[i]['blue']['x']);
}
// and to insert for this sturcture
colors.pink= {x: 150, y: 200};