简体   繁体   English

如何为JavaScript数组的每个元素赋予不同的“类型”?

[英]How to give each element of a JavaScript array a different 'type'?

I have a JavaScript array which contains a number of images. 我有一个包含大量图像的JavaScript数组。 The images have all been taken from a hidden section in my HTML using lines such as 这些图像都是使用以下行从我HTML的隐藏部分中获取的:

sources[0] = document.getElementById("building").src

The reason I am getting the images from the HTML rather than directly from the source is because I want to display around 30 of them on an HTML5 canvas, and if I were to load them directly from source into the JavaScript code, the page would take ages to load, so I've 'preloaded' them in a hidden section of my HTML, and then loaded them into the JavaScript code from there. 之所以要从HTML而不是直接从源获取图像,是因为我想在HTML5画布上显示约30张图像,并且如果要直接从源将其加载到JavaScript代码中,则该页面将需要加载,因此我将它们“预加载”到了HTML的隐藏部分中,然后从此处加载到JavaScript代码中。

So, I have created my JavaScript array with the following: 因此,我使用以下代码创建了我的JavaScript数组:

var sources = [];
sources[0] = document.getElementById("building").src,
sources[1] = document.getElementById("chair").src,
....

(There are roughly 30 lines for adding images to the sources array). (将图像添加到sources数组大约有30行)。

The idea is that there will be four or five different 'types' of image (that is, some will be assets, others will be liabilities, etc.), and the user will be required to drag each image to its corresponding description box (also displayed on the canvas). 这个想法是,将有四种或五种不同的图像“类型”(即,某些将是资产,另一些将是负债等),并且用户将需要将每个图像拖到其相应的描述框中(也显示在画布上)。

So what I'd like to do, is put the images into different 'groups' within the one array. 所以我想做的就是将图像放入一个数组中的不同“组”中。 I've had a look into it, and my understanding is that the best way to do this is by using associative arrays, so, for example: 我已经看过它,而我的理解是,做到这一点的最佳方法是使用关联数组,因此,例如:

var sources = {
    name1 : ["name1", "place1", "data1"],
    name2 : ["name2", "place2", "data2"],
    name3 : ["name3", "place3", "data3"]
};

But I'm not sure how to use this in the context of what I currently have... Would I do something like the following? 但是我不确定如何在当前拥有的环境中使用它...我会做以下事情吗?

var sources = {
    asset1 : document.getElementById("building").src,
    asset2 : document.getElementById("chair").src,

    liability1: document.getElementById("electricity").src,
    ...
};

How would I then check whether an image belongs to the description box it's been dragged to when the user drags it to the description box they think it belongs to? 当用户将图像拖到他们认为属于的描述框中时,我该如何检查图像是否属于该描述框?

The way I intend to check whether an image has been dragged to the correct description box, is to have a Boolean that will be set to "true" when a mousedown event is detected on one of the 'draggable' images, and keep track of the x & y coordinates of the cursor as it moves around the canvas. 我打算检查图像是否已拖到正确的描述框中的方式是让布尔值在检测到“可拖动”图像之一上的mousedown事件时将其设置为“ true”,并跟踪光标在画布上移动时的x和y坐标。

Then, when the mouseup event is triggered, I will check what the coordinates of the cursor are at that point. 然后,在触发mouseup事件时,我将检查光标在该点的坐标。 If the cursor has dropped the image to a location at which one of the description boxes are drawn (so for example, x being between 50-100 and y between 150-200 is where the assets description box is, liabilities description box at x 150-200, y 150-200), then I will check which description box is at that location (loop through the array of description box locations, and check which one is at the location of the cursor, if any). 如果光标将图像放到绘制描述框之一的位置(例如,x在50-100之间,y在150-200之间,则为资产描述框,负债描述框为x 150 -200,y 150-200),那么我将检查哪个描述框位于该位置(遍历描述框位置的数组,并检查哪个位于光标位置(如果有))。

Once I have the name of the description box at that location, I will check to see what 'type' the image that has just been dropped was, and if it matches the box at the location at which it's been dropped, it will disappear from the canvas, if not, it will be drawn back where it was originally 'picked up' by the user. 在该位置获得描述框的名称后,我将检查以查看刚刚放置的图像的“类型”,如果与放置位置的框匹配,它将从如果没有,画布将被拉回最初由用户“拾取”的位置。

What I'm not sure about with how to do this, is how do I access the 'type' of image that the user has clicked on from the array? 我不确定如何执行此操作,该如何访问用户从数组中单击的图像的“类型”?


Edit 2013-03-13T14:15 编辑2013-03-13T14:15

So I've given the suggested answer a go. 因此,我给出了建议的答案。 However, when I now view my page in the browser, the canvas is not displayed, and I get an "uncaught exception" error in the console. 但是,当我现在在浏览器中查看页面时,不显示画布,并且在控制台中收到“未捕获的异常”错误。 This error message says: 此错误消息说:

uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: file:///M:/year%205/major%20project/development/collision/kinetic.js :: :: line 4250" data: no] 未捕获的异常:[异常...“组件返回失败代码:0x80040111(NS_ERROR_NOT_AVAILABLE)[nsIDOMCanvasRenderingContext2D.drawImage]” nsresult:“ 0x80040111(NS_ERROR_NOT_AVAILABLE)”“位置:” JS框架:: file:/// M:/ year%205 /major%20project/development/collision/kinetic.js :: :: 4250行“数据:否]

I'm wondering if this is because of the functions I'm calling at the end of this function...? 我想知道这是否是由于我在此函数结尾处调用的函数引起的? To explain things a bit further, I'm creating and using the sources array inside the window.onload function. 为了进一步解释,我在window.onload函数中创建并使用了sources数组。 It currently looks like this: 当前看起来像这样:

window.onload = function(){
    var sources = {
        assets: [],
        liabilities: [],
        income: [],
        expenditure: []
    }
    console.log("the code reaches here");
    sources.assets[0] = document.getElementById("building").src,
    sources.assets[1] = document.getElementById("chair").src,
    sources.assets[2] = document.getElementById("drink").src,
    sources.assets[3] = document.getElementById("food").src,
    sources.assets[4] = document.getElementById("fridge").src,
    sources.assets[5] = document.getElementById("land").src,
    sources.assets[6] = document.getElementById("money").src,
    sources.assets[7] = document.getElementById("oven").src,
    sources.assets[8] = document.getElementById("table").src,
    sources.assets[9] = document.getElementById("van").src,

    sources.liabilities[10] = document.getElementById("burger").src,
    sources.liabilities[11] = document.getElementById("chips").src,

    /* I have loads of lines like this, adding in roughly 30 images */

    /*Maybe create an array of attributes within each position
      of this array, so that I have access to all of each
      element's attributes. */

    /*Create an associative array for the images and their types*/
    var imageTypes = new Array();

    /*Use a loop to populate the associative array, declare variables for the total number
      of items in each group, declare a variable for the item being for example: */

    var numAssets = 10;
    var numLiabilities = 5;
    var numEx = 11;
    var numInc = 8;

    // Error checking- check total of these numbers adds up to the number elements in sources array.

    var j = 0; // This is to indicate the location of the image in sources array

    loadImages(sources, drawImage);
    drawGameElements();
    drawDescriptionBoxes();
    //drawBox();

    stage.add(imagesLayer);
};

Is the canvas now not showing because of one of the other functions I'm calling at the end of the window.onload function? 由于我在window.onload函数末尾调用的其他函数之一,画布现在没有显示吗? But these function calls were performing correctly before I changed my sources array, so maybe it something wrong with what I've changed in the sources array? 但是在我更改sources数组之前,这些函数调用已正确执行,所以也许我对sources数组所做的更改有问题吗?

I'd suggest restructuring your sources object to: 我建议将您的资源对象重组为:

var sources = {
  assets: [],
  liabilities: []
};

sources.assets[0] = document.getElementById("building").src;
sources.assets[1] = document.getElementById("chair").src;
...
sources.liabilities[0] = document.getElementById("electricity").src;
...

The sources object is optional, you can just have the assets and liabilities arrays. 源对象是可选的,您可以只拥有资产和负债数组。

You can then use this answer: How to determine if object is in array to figure out the 'type' of the selected image. 然后,您可以使用以下答案: 如何确定对象是否在数组中以找出所选图像的“类型”。


Alternatively, you could add a class to the images depending on their 'type' and then check that when the user selects. 或者,您可以根据图像的“类型”向图像添加类别,然后在用户选择时进行检查。

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

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