有没有一种简单的方法可以使用 Javascript 创建动态变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2413414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:12:47  来源:igfitidea点击:

Is there an easy way to create dynamic variables with Javascript?

javascriptdynamic-variables

提问by julio

I've built a data-driven google map with different icons that get assigned to the map depending on the type of item located. So if I have 5 types of landmark, and each gets a different icon (store, library, hospital, etc.)-- what I'd like to do is generate the google icon objects dynamically. I was thinking something like this:

我已经构建了一个数据驱动的谷歌地图,其中有不同的图标,这些图标根据所在项目的类型分配给地图。因此,如果我有 5 种类型的地标,并且每种都有不同的图标(商店、图书馆、医院等)——我想做的是动态生成谷歌图标对象。我在想这样的事情:

types = array('hospital','church','library','store',etc);
var i=0;
while (i<=types.length) {

    var landmark + i = new google.maps.Icon();
    landmark.image = "icon" + i + ".png";
    i++;
    } 

however, as you've probably guessed, this doesn't work. I also tried using eval, like this:

但是,正如您可能已经猜到的那样,这是行不通的。我也尝试使用 eval,如下所示:

while (i<=types.length) {
        doIcon(i);
        i++;
    }   

    function doIcon(i){ 
        eval("var landmark" + i + " = new.google.maps.Icon();");
        return eval("landmark" + i);
    }

but it didn't work either-- I'd appreciate any pointers on generating javascript variables dynamically. It's got to be pure js, I could do it in PHP but that's not an option here.

但它也不起作用——我很感激任何关于动态生成 javascript 变量的指针。它必须是纯 js,我可以用 PHP 来完成,但这不是这里的选择。

Thanks!

谢谢!

回答by Plynx

It's really easy to do: object["variablename"] = whatever;

这真的很容易做到: object["variablename"] = whatever;

So for example you could have an object: var Landmarks = {}and you could add to it like so: Landmarks["landmark" + i] = new google.maps.Icon();and pass it that way.

例如,您可以拥有一个 object:var Landmarks = {}并且您可以像这样添加它:Landmarks["landmark" + i] = new google.maps.Icon();并以这种方式传递它。

If you need these variables to be global(why would you?) you can access the global object directly using window.

如果您需要将这些变量设为全局变量(为什么要这样做?),您可以直接使用window.

回答by Andy E

If you're going to do it using a declared object such as Landmark["landmark" + i], you really may as well use an index array rather than an associative, it's much easier for iteration. Objects aren't really used with indexed properties because Arrays do a much better job of it:

如果您打算使用诸如 之类的声明对象来执行此操作Landmark["landmark" + i],那么您真的还不如使用索引数组而不是关联数组,这样迭代起来要容易得多。对象并没有真正与索引属性一起使用,因为数组在这方面做得更好:

var myObj =           // object version
{
   "item0": "blah",
   "item1": "blah"
   // etc
}
var myArr =           // array version
[
   "blah",
   "blah"
   // etc
]

Much more sensible to use the array:

使用数组更明智:

landmarks = []; // new array
types = array('hospital','church','library','store',etc);  
var i=0;  
while (i<=types.length) {  
    landmarks.push(new google.maps.Icon());
    landmarks[i].image = "icon" + i + ".png";
    i++;  
}

It makes more sense to do it that way and for...inloops on objects can get a bit messy with prototyped properties being enumerable, etc.

这样做更有意义,并且for...in对象上的循环可能会因原型属性可枚举等而变得有点混乱。

If you're trying to make a variable global, add it to the window object:

如果您尝试将变量设为全局变量,请将其添加到 window 对象中:

var myCustomVar = "landmark" + i;
window[myCustomVar] = new google.maps.Icon();

alert(landmark0);

But this would be polluting the global namespace with many unnecessary variables. So you'd still be better with an array:

但这会用许多不必要的变量污染全局命名空间。所以你仍然会更好地使用数组:

window.landmarks = [];
landmarks.push(new google.maps.Icon());
// etc...

回答by Felix

Just to answer your question directly (although please note that this is not the solution you want. Check out the other answers. This is just for documentation!), here's a copy-paste from a JavaScript console:

只是为了直接回答您的问题(尽管请注意,这不是您想要的解决方案。查看其他答案。这仅用于文档!),这是来自 JavaScript 控制台的复制粘贴:

> window["myNamedVar"] = "Hello, World!";
> console.log(myNamedVar);
  "Hello, World!"

回答by leepowers

You'd be better off creating a javascript object which you can use somewhat like an associative array is used in PHP:

你最好创建一个 javascript 对象,你可以使用它有点像在 PHP 中使用的关联数组:

var types = ['hospital','church','library','store'];
var landmarks= {};
for (var i in types) {
    landmarks[types[i]]= new google.maps.Icon();
    landmarks[types[i]].image = "icon" + i + ".png";
} 
alert(landmarks['hospital'].image);  // displays "icon0.png"

回答by Alfgaar

Do you really need those variables? Can't you do with this:

你真的需要这些变量吗?你不能这样做:

var types = ['hospital','church','library','store'];    
for(var i =0; i < types.length; i += 1) (new google.maps.Icon()).image = "icon" + i + ".png";

Modifications done based on comment:

根据评论所做的修改:

icon name pattern changed from icon + index + .png to icon + type + .png and saving the results of the loop.

图标名称模式从 icon + index + .png 更改为 icon + type + .png 并保存循环的结果。

types = ['hospital','church','library','store'];
var landmarks = {};


// images names are of the form icon + type + .png
function createIcon(type) 
{ 
    var icon = new google.maps.Icon();
    icon.image = "icon" + type + ".png";
    return icon;
}

// mapping of landamarks by type and icon
for (var i = 0, len = types.length; i < len; i++)
{
    landmarks[types[i]] = createIcon(types[i]);
}

the result is : { hospital : icon, church : icon, ... }

结果是:{医院:图标,教堂:图标,...}

where icon is a google map icon that has an image attribute that is a string of the form "icon{type}.png" , e.g, iconhostpital.png, iconchurch.png.

其中 icon 是一个谷歌地图图标,它有一个图像属性,它是一个 "icon{type}.png" 形式的字符串,例如 iconhostpital.png、iconchurch.png。

To use the icons write landmarks.typewhere type is one the names in the array of types, e.g. landmarks.hospital.

要使用图标landmarks.type,请在类型数组中写入其中一个类型的名称,例如landmarks.hospital

if the image names are of the form icon + number + .png, and the number for each type is equivalent to its index in the array replace the call createIcon(type[i]) for createIcon(i).

如果图像名称的形式为图标 + 数字 + .png,并且每种类型的数字等同于其在数组中的索引,请替换对 createIcon(i) 的调用 createIcon(type[i])。