简体   繁体   English

在javascript中从用户获取变量的名称

[英]get name of variables from user in javascript

I have an object that name is "car":我有一个名称为“汽车”的对象:

function car(name) {
    this.name = name;
    this.position= 0;
}

i get the number of cars from user:我从用户那里得到汽车的数量:

let nubmerOfCars = +prompt("Input Number of Casr")

and create cars to the number entered with name that user entered for each one the end, push cars to array:并根据用户输入的名称创建汽车,最后将汽车推入数组:

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

but, i want for each car, create a variable with user entered name, such it:但是,我想为每辆车创建一个带有用户输入名称的变量,例如:

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{...};

really i want create variables that the user has entered names can i do this?我真的想创建用户输入名称的变量我可以这样做吗?

You cannot create variable names that way, workaround could be to create an object:您不能以这种方式创建变量名称,解决方法可能是创建一个对象:

 let carsArray=[{name:"a"},{name:"b"},{name:"c"}] let carObj = {}; carsArray.forEach((car) => { carObj[car.name]=car }); console.log(carObj)

There is no direct way to add variables named by javascript itself to the local scope.没有直接的方法可以将 javascript 本身命名的变量添加到本地范围。 But usually the global scope exists as an object instance, and this is changeable.但通常全局范围作为对象实例存在,这是可变的。 Like window on client site JS:像客户端站点JS上的window

// set variable x using the window object
window.x = "This is the value of x";
// accessing window.x only writing x
alert(x); // will alert: This is the value of x

// use string to define a variable name
window["y"] = "test";
// accessing...
alert(y); // will alert: test

// using other variable to define variable name
window[y] = 123;
// accessing...
alert(test): // will alert: 123

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

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