在Javascript中获取关联数组的索引

Huu*_*ons 1 javascript arrays indexing associative-array javascript-events

所以我有一组"关联数组",即.对象,包含各种HTML元素的数据和其他一个参数,如下所示:

container[0] = { picker_canvas: document.getElementById("background_picker"),
                 color_canvas: document.getElementById("background_color"),
                 hex_text: document.getElementById("background_text"),
                 mouse_down: false };

container[1] = { picker_canvas: document.getElementById("textbox_picker"),
                 color_canvas: document.getElementById("textbox_color"),
                 hex_text: document.getElementById("textbox_text"),
                 mouse_down: false };

container[2] = { picker_canvas: document.getElementById("font_picker"),
                 color_canvas: document.getElementById("font_color"),
                 hex_text: document.getElementById("font_text"),
                 mouse_down: false };
Run Code Online (Sandbox Code Playgroud)

每个容器都有一个颜色选择器画布,一个颜色预览画布,一个显示十六进制颜色值的文本框和一个mouse_down布尔值的引用.稍后我通过遍历容器来初始化一些事件监听器,如下所示:

for (i=0; i<3; i++) {

    container[i].picker_canvas.addEventListener("mousedown", function() {
        container[i].mouse_down = true;
    }, false);

    container[i].picker_canvas.addEventListener("mouseup", function() {
        container[i].mouse_down = false;
    }, false);

    container[i].picker_canvas.addEventListener("mousemove", function(evt) {
        getColor(container[i], evt);
    }, false);

    container[i].hex_text.addEventListener("change", function(evt) {
        drawColorSquare(container[i], evt.target.value)
    }, false);

}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为我变得未定义,所以我现在试图通过做这样的事情来获得正确的索引,但我不知道如何在javascript中实际实现它

container[i].picker_canvas.addEventListener("mousedown", function(evt) {
    container[container.indexof(evt.target)].mouse_down = false;
}, false);
Run Code Online (Sandbox Code Playgroud)

基本上我需要搜索evt.target的关联数组数组并让它返回数组的索引.因此,任何内置的javascript函数都可以实现这一点,或者我只需要创建自己的函数?

Ry-*_*Ry- 6

由于您似乎不必担心Internet Explorer 8及更早版本,因此请使用forEach:

container.forEach(function(x) {
    x.picker_canvas.addEventListener("mousedown", function() {
        x.mouse_down = true;
    }, false);

    x.picker_canvas.addEventListener("mouseup", function() {
        x.mouse_down = false;
    }, false);

    x.picker_canvas.addEventListener("mousemove", function(evt) {
        getColor(x, evt);
    }, false);

    x.hex_text.addEventListener("change", function(evt) {
        drawColorSquare(x, evt.target.value)
    }, false);
});
Run Code Online (Sandbox Code Playgroud)