与 getURLVars() 相对应,用于简化变量
我正在使用 此函数 来抓取我的网址并从中构建变量:
读取页面的 GET URL 变量并 将它们作为“关联数组”返回。 在 at 时调用该函数 example.html?foo=asdf&bar=jkls 集 地图['foo']='asdf' 和 地图['bar']='jkls'
我如何添加 for 循环以便这样
foo = map['foo']
bar = map['bar']
?
第一个解决方案不起作用。
I am using this function to scrape my url and build variables from it:
Read a page's GET URL variables and
return them as an "associative array."
Calling the function while at
example.html?foo=asdf&bar=jkls sets
map['foo']='asdf' and
map['bar']='jkls'
how would I add a for loop so that
foo = map['foo']
bar = map['bar']
?
First solution didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样循环遍历地图
这将创建 window[foo] 和 window[bar],它们与 window.foo 和 window.bar 相同,它们与 foo 和 bar 相同。
编辑:以下是我正在使用的测试页面中的正文内容。 jQuery 应该加载到 head 中,只是因为我用它来初始化我的测试并附加一个单击处理程序,但 for 循环的概念并不依赖于 jQuery。由于我没有地图,因此我在加载文档时自己创建它。从那时起,我将按照我所描述的方式循环遍历地图,并将单击处理程序附加到按钮以测试正确的分配。
You can loop through the map like this
This would create window[foo] and window[bar], which are the same as window.foo and window.bar, which are the same as foo and bar.
EDIT: Here are the contents of the body in the test page I'm using. jQuery should be loaded in the head only because I use it to initialize my test and attach a click handler, but the concept of the for loop is not dependent on jQuery. Since I don't have the map coming into me, I am creating it myself when the document loads. From that point, I am looping over the map just as I described and attaching a click handler to a button to test the proper assignment.
为什么你想用所有这些变量破坏全局命名空间?使用
map.foo
和map.bar
有什么问题? — 您确实知道map['foo']
和map.foo
完全相同吗?而且,你想要的东西是非常不安全的。如果有人使用 URL 查询参数
?%24=test
打开您的页面,您就会被搞砸:jQuery 将不再工作,因为您已经覆盖了$
全局变量。另外,请记住,URL 参数通常不区分大小写,但 Javascript 是区分大小写的。因此,通常
?KEY=value
与?key=value
相同。然而,map.key
和map.KEY
被视为不同的变量。Why would you want to clobber the global namespace with all those variables? What is wrong with using
map.foo
andmap.bar
? — You do know thatmap['foo']
andmap.foo
are exactly the same?Besides, what you want is very unsecure. If someone opened your page with URL query parameters
?%24=test
you’d be screwed: jQuery wouldn’t work anymore since you’d have overwritten the$
global variable.Also, keep in mind that URL parameters are normally not case-sensitive, but Javascript is. So, usually
?KEY=value
will be the same as?key=value
.map.key
andmap.KEY
, however are treated as different variables.