简体   繁体   中英

Passing variables into an Object in Javascript

I am trying to pass a variable into an Object so that the property's value is the variable I passed in.

var car = {
  make: 'Jeep',
  model: 'Renegade',
  year: yearVar
}

var yearVar = 2016;
console.log(car.year); //says year is undefined

So how do I set the property of the car Object equal to the yearVar variable?

undefined is not an error. It's saying undefined because at the line you assign the value of yearVar to the object, the variable yearVar is not defined yet so it will assign undefined instead. (defining the variable afterwards won't solve the problem because undefined is already assigned). What you need to do is:

// define yearVar first
var yearVar = 2016;

var car = {
  make: 'Jeep',
  model: 'Renegade',
  year: yearVar // then use it afterwards (after it's been defined)
}

Declare variable yearVar and assign its value before you create car object.

 var yearVar = 2016; var car = { make: 'Jeep', model: 'Renegade', year: yearVar } console.log(car.year)

You will need to declare and set the yearVar varible before defining the car object. Javascript executes top to bottom Doing something like this would surely work

var yearVar = 2016;

var car = {
  make: 'Jeep',
  model: 'Renegade',
  year: yearVar
}

console.log(car.year);

To change after car has been created:

var car = {
  make: 'Jeep',
  model: 'Renegade',
  year:null
}

car.year = 2016;

console.log(car.year);

Though the problem is solved I am sharing something new but it is correct. This is a technique used by the JavaScript engine called hoisting.

 yearVar = 2016; //check the var declaration in the bottom var car = { make: 'Jeep', model: 'Renegade', year: yearVar } var yearVar; console.log(car.year);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM