Home > other >  how to declare multiple variables with the same value
how to declare multiple variables with the same value

Time:12-06

in order to prevent creating every single variable with same type I declared them this way:

  data () {
    return {
      today,tomorrow: new Date(),
    };
  },
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

all I get in my intellij terminal is an error

error 'today' is not defined no-undef

have I mistaken the syntax or the process is not possible ?

CodePudding user response:

Simple. you can't. In JS object and JSON syntaxt you can't declare and init many varialbes in one expression.

if you need many vars with the same value, just return it from setup function.

setup(){
   const now = new Date();
   return {
      today: now,
      tomorow: now
   }
}

you can create it in "create" function.

created(){
   this.today = new Date();
   this.tomorrow = new Date();
}

But be aware. Date is instance of Data class. So if two variables points to it, then you have to remember that changing props of today will affect tomorrow. Eg. if your today and tommorow variables points to one Date object then today.setHours will affect tommorow as well.

CodePudding user response:

You are returning an object, in an object by using the comma , you are listing different properties of the object, since you don't define today before typing the comma, you tell the object that today is now undefined.

It is better to just declare both properties or not use an object.

function data() {
  let sameVariable = new Date();
  return {
    today: sameVariable,
    tomorrow: sameVariable,
  };
}

This way you can now acces the variables with obj.today and obj.tomorrow

Maybe take a look in how objects work (thats when returning something with {...}) You are returning an Object in your example

  • Related