gpt4 book ai didi

javascript - 将字符串转换为本地 jQuery 变量

转载 作者:行者123 更新时间:2023-11-29 19:09:23 25 4
gpt4 key购买 nike

我正在尝试将字符串转换为变量名,在本例中为数组。通常我会用 window[var] 来做,但我在 jQuery 中工作:

$(function() {
var myArray = new Array();
var myArrayName = 'myArray';
console.log(window[myArrayName]); // undefined
});

这似乎不起作用,因为 myArray 位于 jQuery 范围内。

我知道我可以将 myArrayName 声明为全局变量以从任何地方访问它,但我不想这样做,因为我想避免全局命名空间污染。

有没有办法在 jQuery 中将字符串转换为变量?

最佳答案

您可以在 $(document).ready() 方法中使用 this 来指向 Document 对象。它的工作原理如下:

    <script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(evt){
// this HERE POINTS TO THE DOCUMENT OBJECT
this.myArray = new Array();
this.myArrayName = 'myArray';
console.log(this); // #document (Object)
console.log(this[this.myArrayName]); // [] (Array)
});
})(jQuery);

</script>

So, anywhere within the $(document).ready() Method, you can always access the value either of the following ways:

         var doc    = $(document);
var arr1 = this[this.myArrayName]; //<== ASSUMES this POINTS TO DOCUMENT OBJ.
var arr2 = doc[doc.myArrayName]; //<== USES $(document) DIRECTLY

关于javascript - 将字符串转换为本地 jQuery 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com