Home > OS >  How to get the result in a function out in javascript?
How to get the result in a function out in javascript?

Time:09-16

var data = null;
function dataReal(val) {
  data = JSON.parse(val);
  console.log(data); // Result object : {users: Array(3), permission: Array(8)}
}
console.log(data); // Result : null

How do I get that result outside the function : dataReal

var data = null;
function dataReal(val) {
  data = JSON.parse(val);
  console.log(data); // Result object : {users: Array(3), permission: Array(8)}
}
dataReal(val); // Call this function before accessing
console.log(data);

CodePudding user response:

you are missing one step here :)

your data is undefined because you did not invoke the function, so data is not assigned properly and remains null/undefined

you can try to pass in your parameters into dataReal, and then invoke the function after that

var data = null;
function dataReal(val) {
  data = val;
  //console.log(data); // Result object : {users: Array(3), permission: Array(8)}
}

dataReal({users: ["user-1", "user-2", "user-3"], permission: [0, 1, 2, 3, 4, 5, 6, 7, 8]})

console.log(data);

  • Related