[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2583
  • Last Modified:

Check is array exists IF Not create one

Hello,
This may be a simple question but I'm unable to find the information I need to make it work.

I want to create an array however, only if the array doesn't already exist.

Something like this...


function updateArray(){
            if (ARRAY DOESNT EXIST) {
            var appendValue = document.getElementById('msgdiv').innerHTML;
            ansArray.push(appendValue);
                  
            }else{

            var ansArray =[];
            var appendValue = document.getElementById('msgdiv').innerHTML;
            ansArray.push(appendValue);
            alert('Array Length: '+ansArray.length);
      }            
}
0
cubicalmonkey
Asked:
cubicalmonkey
1 Solution
 
basicinstinctCommented:
if the array is called 'myArray' then like this:

if(myArray == null)
0
 
basicinstinctCommented:
but i think you meant to say  this:

if (ARRAY EXISTS)

which is this:

if(ansArray != null)  
0
 
DiscoNovaCommented:
@basicinstinct: no... that may work sometimes, but fails miserably on others...

if (typeof myArray == "undefined")

... might work a bit better (but not much:)
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
frindoCommented:
I would actually define the array regardless and then just put data in accordingly.

So it would be like this:

var ansArray =[];
function updateArray(){
            var appendValue = document.getElementById('msgdiv').innerHTML;
            ansArray.push(appendValue);    
}

Far fewer lines of code.
0
 
basicinstinctCommented:
if you want to get fancy you could do this:

if(ansArray instanceof Array)
0
 
DiscoNovaCommented:
Also, an item can be something else than null, but still not be an array - it might even be an arraylike object, but still fail to act like an array sometimes (objects behave very closely like arrays, but lack certain functionality arrays have and depend on).

I'd write the function like this (even this solution is not perfect):

function updateArray(){
  andArray = ansArray || []; // Initialize if not exists
  var appendValue = document.getElementById('msgdiv').innerHTML;
  ansArray.push(appendValue);
  alert('Array Length: '+ansArray.length);
}
0
 
DiscoNovaCommented:
Oh bugger that the comments don't update in realtime :)
0
 
gops1Commented:
Try this sample code. First click of the button, checks if the array is defined, if not creates and adds divs value to it. Second click, the array is found and appends one more value to the array.

<html>
      <head>
            <title>Script Demo Gops</title>
            <script language="javascript">
                  function updateArray(){
                        if(document.ansArray==undefined){
                              alert("Array does not exist..Creating..");
                              document.ansArray=new Array();
                              document.ansArray.push(document.getElementById('msgdiv').innerHTML);
                              alert("Array successfully created: \n"+document.ansArray);
                        }else{
                              alert("Array exist");
                              document.ansArray.push("2nd Value");
                              alert("Array values appended: \n"+document.ansArray);
                        }
                  }

            </script>
      </head>
<body>
      <div id='msgdiv'>Div Item</div>
      <input type="button" value="Update Array" onclick="updateArray()">
</body>
</html>
0
 
cubicalmonkeyAuthor Commented:
Thank you everyone for your replies.
I've used gops1's suggestion which is working exactly how I wanted.

basicinstinct:
Yes you are correct, my function in the original post was reversed.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now