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

编程入门 行业动态 更新时间:2024-10-24 23:15:42
本文介绍了有没有一种简单的方法来使用Javascript创建动态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

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++; }

然而,正如您可能已经猜到的那样,这不起作用。我也试过使用eval,如下所示:

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

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

但它也不起作用 - 我很感激任何关于动态生成javascript变量。它必须是纯粹的js,我可以用PHP来做,但这不是一个选项。

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.

谢谢!

推荐答案

这很容易做到: object [variablename] = what;

所以例如你可以有一个对象: var Landmarks = {} 你可以像这样添加它: Landmarks [地标+ i=新的google.maps.Icon(); 并以这种方式传递。

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.

如果你需要这些变量 global (为什么会这样?)您可以使用窗口直接访问全局对象。

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

更多推荐

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

本文发布于:2023-10-27 23:35:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法来   变量   简单   动态   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!