如何在此对象/数组中搜索获取字段名称的第一个元素?
在此示例中,如果我要搜索second
#999999
colors = {
first: ['#cccccc', '#999999'],
second: ['#999999', '#626262'],
third: ['#eeeeee', '#afafaf']
};
我试过这样的事情:
for(var field in colors) {
if(colors.hasOwnProperty(field)) {
if(colors[field] === '#999999') {
console.log(field); // gives 'second'
var color1 = colors[field][0],
color2 = colors[field][1];
}
}
}
也许这会更简化。
答案 0 :(得分:1)
尝试使用Object.keys()
,Array.prototype.filter()
;返回"#999999"
位于数组<{p>}的索引0
的对象的属性名称
var colors = {
first: ['#cccccc', '#999999'],
second: ['#999999', '#626262'],
third: ['#eeeeee', '#afafaf']
};
var n = "#999999";
var res = Object.keys(colors).filter(function(key, index) {
return colors[key][0] === n
});
console.log(res[0])
&#13;
答案 1 :(得分:0)
colors[field]
是整个数组。你忘了测试Array元素。你的循环看起来应该更像:
for(var field in colors){
if(colors[field][0] === '#999999'){
console.log(field); // gives 'second'
}
}
答案 2 :(得分:0)
如果要在该阵列位置找到该搜索参数的所有键名,请使用数组捕获它们。这是一个通用函数来解决这个问题,以防你在那个位置有多个具有该参数的数组。
var canvas = <HTMLCanvasElement>document.getElementById('myCanvas');
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0);
}
img.src = "zombie.png";
var mapArray =
["############################",
"# # # o ##",
"# #",
"# #### ##### ## #",
"## # # ## #",
"### ## # #",
"# ### # #",
"# #### ### #",
"# ## # o #",
"# o # # o ### ### #",
"# # # #",
"############################"];
//need to add wall.scource = and grass.source =
var wall = new Image();
var grass = new Image();
grass.src = "http://vignette2.wikia.nocookie.net/tibia/images/6/60/Grass_(Tile).gif/revision/latest?cb=20080817072800&path-prefix=en";
wall.src = "https://s-media-cache-ak0.pinimg.com/236x/74/37/22/74372202cfd397f5fbd004fc45d83ca3.jpg";
var posX = 0;
var posY = 0;
context.rect(posX, posY, 50, 50)
context.stroke();//traces path, might not need this
function move(e) {
alert(e.keycode);//gives feedback to what each keydcode is, but doesn't work
if (e.keycode == 39) {
posX += 5;
}
if (e.keycode == 37) {
posY += 5;
}
canvas.width = canvas.width;
context.rect(posX, posY, 50, 50)
context.stroke();
}
document.onkeydown = move;