How to push values to array in one function and read it in another function?

24
May 23, 2019, at 07:00 AM

Here is my code:

var myObject = [];
function something() {
    myObject.push("thing");
}
function other() {
    console.log(myObject);
}

How can I let other see the items pushed into myObject by something?

Answer 1

It's declared globally - so just calling something() then other() will ensure that there are elements in the array. If you were calling them in the wrong order, then the function was displaying the empty array first, then adding an element to it.

var myObject = []; 
 
function something() { 
  myObject.push("thing"); 
} 
 
function other() { 
  console.log(myObject); 
} 
 
something(); 
other();

If you want to log each item on a separate line:

var myObject = []; 
 
function something() { 
  myObject.push("thing"); 
} 
 
function other() { 
  myObject.forEach(e => console.log(e)); 
} 
 
something(); 
something(); 
something(); 
other();

Also, you're dealing with an array, not an object. An object looks like this:

var anObject = { 
  key1: "value1", 
  key2: true, 
  key3: 42.01 
}; 
 
console.log(anObject);

READ ALSO
Javascript Switch-Case syntax is confusing me [duplicate]

Javascript Switch-Case syntax is confusing me [duplicate]

This question already has an answer here:

50
How do we make an elliptic terrain with matter.js?

How do we make an elliptic terrain with matter.js?

I am trying to use matterjs in order to make an elliptic terrain which can have many bodies in it

50
Errors Creating Simple Azure HDInsight Spark Cluster with Pulumi

Errors Creating Simple Azure HDInsight Spark Cluster with Pulumi

I am attempting to use the Pulumi Javascript SDK to create a HDInsight Spark Cluster on AzureI have followed the tutorials Pulumi provides on creating a "hello world" GCP Kubernetes cluster and gone through the JavaScript examples in the Pulumi Examples...

33
Possible to extract javascript from website?

Possible to extract javascript from website?

I need help getting an advice if it is possible to get the javascript code for this pageI am not looking for anyone to write code, just say if it is possible

49