1

アイテムごとに 3 つのデータを持つ色構造を構築しようとしています。たとえば、赤には x と y があり、青には x と y があります。したがって、3 つのデータは次のようになります。color, x, y

色に基づいて x と y を読みやすくするには、どのような構造が必要ですか。私は通常そうしますpush(color, x, y)が、ループする必要なく色ですばやく検索する必要があるため、ここでは機能しません。ここで必要な構造と、それを設定して取得する方法。

4

5 に答える 5

4

単純なオブジェクト (ハッシュ) はどうですか?

// 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']);

それとも私はあなたを間違って理解しましたか?

于 2012-05-27T07:39:29.397 に答える
3

辞書のようなものをお探しですか?!?

var colorArray = {};
colorArray["red"] = {
    x: 100,
    y: 200
};
colorArray["blue"] = {
    x: 222,
    y: 200
};
alert(colorArray["red"].x);​
于 2012-05-27T07:40:57.130 に答える
2

または、配列にも色が必要な場合

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 };
 ...
于 2012-05-27T07:48:19.260 に答える
2
var colors = {
    red  : { x : 42, y : 7 },
    blue : { x : .., y : .. },
    ...
};

alert(colors.red.x);
于 2012-05-27T07:40:08.270 に答える
1
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};
于 2012-05-27T07:42:51.577 に答える