Jayadeep L
Jayadeep L

Reputation: 1

Send a value into an array using Variable in JavaScript

function fun(){
    var a=10;
    var b=20;
    document.getElementById("output1")=a;
    document.getElementById("output2")=b;
  }

This is a JavaScript function

var Data = [{label="1", value=output1},{label="2", value=output2}];

I want the values of a and b to be used in the array Data. But I am unable to access it. Hope one will get through this soon.

Upvotes: 0

Views: 112

Answers (3)

arizafar
arizafar

Reputation: 3122

Rather making changes in your existing scope of variables,

You can return the values from fun and then use it in another function where you are creating data;

function fun(){
	var a=10;
	var b=20;
	//document.getElementById("output1")=a;
	//document.getElementById("output2")=b;
	return [a, b];
}

var ab = fun();
var Data = [{label: "1", value: ab[0]},{label: "2", value: ab[1]}];
console.log(Data)

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44107

a and b in this context will be local to the function - you have to define them outside the function. Also make sure your object properties are in the format key: value instead of key = value:

var a, b;
function fun() {
  a = 10;
  b = 20;
  document.getElementById("output1").innerText = a;
  document.getElementById("output2").innerText = b;
}

fun();

var Data = [{
  label: "1",
  value: a
}, {
  label: "2",
  value: b
}];

console.log(Data);
<p id="output1"></p>
<p id="output2"></p>

Upvotes: 0

ellipsis
ellipsis

Reputation: 12152

Define a and b outside the function. Call the function to assign them values. In the Data array instead of = use : to give values to properties in object

var a;
var b;
function fun(){
    a=10;
    b=20;
   // document.getElementById("output1")=a;
   // document.getElementById("output2")=b;
  }
fun()

var Data = [{label:"1", value:a},{label:"2", value:b}];
console.log(Data)

Upvotes: 1

Related Questions