1

I have an external javascript function that just declares an empty array. I have two files that use this array, the first one appends to the array using the push method, the second one searches through the array and looks for the values added to the array, if it's there. My problem is that every time I try to search the array, It comes up empty, which means nothing is added to the array.

This is the content of my .js file:

   var users = [];

This is the javascript part of my .html file:

  <script type="text/javascript" src="array.js"></script>
  <script type="text/javascript">
           var uname = "someone";
           var pword = "something";
           users.push(uname);
           users.push(pword);
  </script>
5
  • 1
    When do you try to search the array? Commented Mar 30, 2013 at 18:24
  • After adding to the array. Commented Mar 30, 2013 at 18:27
  • You would have to add the search script at the end of everything. Commented Mar 30, 2013 at 18:28
  • Create a jsFiddle.net example. For your examples I can see You only add data o your array. Commented Mar 30, 2013 at 18:29
  • If you are referencing the array-creation-script from two different files, that does not mean you are working with the same array object. Commented Mar 30, 2013 at 19:35

1 Answer 1

1

I suggest you to namespace your application to avoid conflicts. The following would help:

//array.js
var myApp = {
    users: [] //This will create a new var users with empty array
};

//JS in the HTML file
<script type="text/javascript" src="array.js"></script>
<script type="text/javascript">
    var uname = "someone";
    var pword = "something";
    if (myApp && myApp.users) {
        myApp.users.push(uname);
        myApp.users.push(pword);
    }
</script>

Also I suggest you to load array.js at the top of your HTML and place the inline script at the end of the HTML.

Sign up to request clarification or add additional context in comments.

2 Comments

myApp variable is not being acknowledged.
Figured out what I was doing wrong. It works now, thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.