简体   繁体   English

Javascript 的新手。 尝试从字符串数组创建图像对象数组时遇到问题

[英]New-ish to Javascript. Having an issue trying to make an array of image objects from an array of strings

Unsure if I am using the correct words to describe what I am attempting to do so its difficult to find an answer on here to my issue.不确定我是否使用正确的词来描述我正在尝试做的事情,因此很难在这里找到我的问题的答案。

I have an array which is being generated from a text file in the form of tempData, and I want the array to reference my variables that are named the same as the strings when I reference them.我有一个数组,它是从 tempData 形式的文本文件生成的,我希望该数组在我引用它们时引用与字符串命名相同的变量。

 var red = new Image(), blue = new Image(), bag = [], tempData = ''; red.src='link to image location'; blue.src='link to image location'; tempData = "red\\nblue"; bag = tempData.split("\\n"); console.log(bag);

In the above snippet console.log(bag);在上面的代码片段中 console.log(bag); returns an array of ["red", "blue"] I want it to return [red, blue] such that if I wanted bag[0] I could get red.src.返回一个 ["red", "blue"] 数组我希望它返回 [red, blue] 这样如果我想要 bag[0] 我可以得到 red.src。 From the examples I was looking at it mentioned window and eval both of which I was unable to make do what I wanted.从我看到的例子中提到了 window 和 eval 这两个我都无法做到我想要的。 Is there a way to make this work or am I just implementing them wrong?有没有办法使这项工作正常进行,或者我只是错误地实施了它们?

Create an images object and two property value pairs, one for each image.创建一个图像对象和两个属性值对,每个图像一个。 Then get the images by the key name in the bag array:然后通过 bag 数组中的键名获取图像:

 var images = {}, bag = [], tempData = '', red = new Image(), blue = new Image(); red.src='link to image location'; blue.src='link to image location'; images['red'] = red; images['blue'] = blue; tempData = "red\\nblue"; bag = tempData.split("\\n"); console.log(images[bag[0]].src);

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

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