2

I'm trying to convert a string into a variable name, in this case an array. Normally I would do it with window[var], but I'm working inside jQuery:

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

that doesn't seems to work, because myArray is located inside the jQuery scope.

I'm aware that I could declare myArrayName as a global variable to access it from everywhere, but I don't want to do that because I want to avoid the global namespace pollution.

is there a way to convert a string into a variable inside jQuery?

denoise
  • 1,067
  • 2
  • 14
  • 40
  • You can do this by adding a property to an object, see this answer: http://stackoverflow.com/a/25529838/2181514 – freedomn-m Oct 28 '16 at 10:13
  • 1
    Here's another: http://stackoverflow.com/questions/1664282/javascript-refer-to-a-variable-using-a-string-containing-its-name – freedomn-m Oct 28 '16 at 10:15

2 Answers2

3

You can use this within the $(document).ready() Method to point to the Document Object. Here's how it could work:

    <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
Poiz
  • 7,611
  • 2
  • 15
  • 17
0

thanks to @freedomn-m pointing to @friedo answer https://stackoverflow.com/a/1664294/2466080

I defined my array inside another array like this:

var myHash = { myArray: [] }

and then I used it for referencing the array, so the code turns to this:

$(function() {
  var myHash = { myArray: [] }
  var myArrayName = 'myArray';
  console.log(myHash[myArrayName]);
});
Community
  • 1
  • 1
denoise
  • 1,067
  • 2
  • 14
  • 40