我有一个名称为“ car”的对象:
function car(name) {
this.name = name;
this.position= 0;
}
我从用户处获得了汽车数量:
let nubmerOfCars = +prompt("Input Number of Casr")
并使用用户为每个末端输入的名称创建输入编号的汽车,将汽车推入阵列:
for (i = 0; i < nubmerOfCars; i++) {
let nameCar = prompt("Input name of car no." + `${i+1}` + ":");
let temp = new car(nameCar);
temp.name = nameCar;
nameCar=temp;
carsArray.push(nameCar);
carsArray.push(temp);
}
// user entered a,b,c for cars name
carsArray=[car{name:a},car{name:b},car{name:c}] // for 3 cars
但是,我想为每辆汽车创建一个带有用户输入名称的变量,例如:
function car() { //remove names's key
this.position= po;
}
//user entered a,b,c for cars name
let a = new car{...};
let b = new car{...};
let c = new car{...};
真的我想创建用户输入名称的变量我可以这样做吗?
您不能以这种方式创建变量名,解决方法可能是:
let carsArray=[{name:"a"},{name:"b"},{name:"c"}]
let carObj = {};
carsArray.forEach((car) => {
carObj[car.name]=car
});
console.log(carObj)