简体   繁体   English

如何为一个对象分配许多变量?

[英]How to assign many variables to an object?

I have a lot of variables that are already defined: 我已经定义了很多变量:

var listOfCars = $('#cars');
var car        = $('#currentCar');
var carIndex   = $(car).index();
var isFirstCar = carIndex == 0;
var isLastCar  = carIndex == $(listOfCars).length - 1;
// and many more in real life

And I want to put all of them into an object where the name of the variable is also the name of the key. 我想将它们全部放入一个对象中,其中变量的名称也是键的名称。 This is how I would do it if I wanted to rewrite every line: 如果我想重写每一行,这就是我要这样做的方式:

var params = {
  listOfCars : listOfCars,
  car        : car,
  ...
};

With Sublime I was able to create an array of variable names: 使用Sublime,我能够创建一个变量名数组:

var paramKeys = [ "listOfCars", "car", "carIndex"...];

But I'm stuck on how to assign the actual values easily. 但是我一直坚持如何轻松分配实际值。 I'm hoping to find a one-liner. 我希望找到一个班轮。 Something like this: 像这样:

paramKeys.every( key => param[key] = ????? );

You can do almost the same thing as your array notation by swiping out the brackets for curly braces. 通过扫除花括号的括号,可以执行与数组符号几乎相同的操作。 This will use the names of the variables as keys and the values as values: 这将使用变量的名称作为键,使用值作为值:

 var listOfCars = ["list of cars"] var car = "a car" var carIndex = 26 var isFirstCar = 0 var isLastCar = 10 let obj = {listOfCars, car, carIndex, isFirstCar, isLastCar } console.log(obj) 

Personally I thing it's easier for you to use Property Shorthand: 就我个人而言,使用Property Shorthand更容易:

 var listOfCars = []; var car = "car info"; var params = { listOfCars, car }; console.log(params) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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