JavaScript:关联/对象数组中的indexOf?

时间:2015-02-20 20:54:33

标签: javascript arrays

我有这个数组:

var skins = {};
skins.w = "http://example.com/public/images/char_elements/base.png";

var eyes = {};
eyes.b = "http://example.com/public/images/char_elements/eyes/blue.png";
eyes.g = "http://example.com/public/images/char_elements/eyes/green.png";
eyes.r = "http://example.com/public/images/char_elements/eyes/red.png";

var hair = {};
hair.b = "http://example.com/public/images/char_elements/hair/black.png";
hair.w = "http://example.com/public/images/char_elements/hair/blond.png";
hair.s = "http://example.com/public/images/char_elements/hair/brown.png";

var mouth = {};
mouth.h = "http://example.com/public/images/char_elements/mouth/happy.png";

var pants = {};
pants.s = "http://example.com/public/images/char_elements/pants/shorts.png";

var shoes = {};
shoes.b = "http://example.com/public/images/char_elements/shoes/black.png";

var torso = {};
torso.s = "http://example.com/public/images/char_elements/torso/shirt.png";

这个功能:

function SwitchElement(type){
switch(type){

    case "eyes":
    var cur = eyes.indexOf(document.getElementById(type).src);
    console.log(cur);
//  var eyesId = document.getElementById("
    break;
}
}

所有这些都被称为:

<img class="builder_control_front" src="http://claro.mib.infn.it/arrow.png" onclick="SwitchElement('eyes');"/>

所以基本上当用户点击箭头时,它会调用加载当前图像的javascript函数,获取元素所在的数组索引(在本例中为数组:“eyes”)并循环显示它。

我需要通过url获取索引,当我尝试使用indexOf时抛出Undefined,我读到如果数组已命名索引,JavaScript会将数组转换为Object。

所以我可以获得当前加载图像的索引吗?

注意:我需要有以下代码的数组:b,g,r,w,w4,b3等。 所以改为普通数组不是一个很好的选择,也许更改为多维数组会更好吗?

2 个答案:

答案 0 :(得分:0)

为什么不迭代你的对象并找到包含值的键:

function findKey(obj, value) {
    for (var key in obj) {
        if (obj[key] == value) return key
    }
    return null;
}

var key = findKey(eyes, document.getElementById(type).src);
if (key != null) { 

} else {

}

答案 1 :(得分:0)

您需要的是反向查找。假设您的所有网址都是唯一的,您可以创建一个这样的网址:

function invert(obj) {
    var newObj = {};
    for(var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[obj[key]] = key;
        }
    }
}

var hair = {};
hair.b = "http://example.com/public/images/char_elements/hair/black.png";
hair.w = "http://example.com/public/images/char_elements/hair/blond.png";
hair.s = "http://example.com/public/images/char_elements/hair/brown.png";
var hairReverse = invert(hair);

var url = "http://example.com/public/images/char_elements/hair/black.png";
console.log(hairReverse[url]); // logs "b"

如果你正在使用Lodash / Underscore,它内置invert function

var hairReverse = _.invert(hair);