0
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.

3 Answers 3

1

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)

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

Comments

0

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>

Comments

0

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)

Comments

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.