繁体   English   中英

什么javascript数组,嵌套数组,对象最适合搜索

[英]What javascript array, nested array, object is most suitable for searching

我试图建立一个颜色结构,每个项目具有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 = {
    red  : { x : 42, y : 7 },
    blue : { x : .., y : .. },
    ...
};

alert(colors.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 }
}

您还可以使用字符串“ constants”:

var RED = "red";

var colors = {};
 colors[RED] = { color: RED, x: 100, y: 200 };
 ...
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};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM