我想从这些函数参数中创建新变量。如何做呢?从函数参数
function addNewStudent(firstName,lastName){
var firstName+lastName = new Student();
}
addNewStudent('Hero','Man');
错误消息: 未捕获的SyntaxError:意外的令牌+
我想从这些函数参数中创建新变量。如何做呢?从函数参数
function addNewStudent(firstName,lastName){
var firstName+lastName = new Student();
}
addNewStudent('Hero','Man');
错误消息: 未捕获的SyntaxError:意外的令牌+
制作动态变量需要eval
。这是不好的做法。有更好的选择:
使用对象:
var students={};
function addNewStudent(firstName,lastName){
students[firstName+lastName] = new Student(firstName,lastName);
}
addNewStudent('Hero','Man');
students['HeroMan']; // Student instance
students.HeroMan; // Student instance
var students=new Map();
function addNewStudent(firstName,lastName){
students.add(firstName+lastName, new Student(firstName,lastName));
}
addNewStudent('Hero','Man');
students.get('HeroMan'); // Student instance
与所述对象的地图,你甚至可以看到整个列表通过访问students
。这不是更方便,更合理吗?
通过上述@dfsq的建议,我会建议的解决方案:
function Student(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var student1 = new Student('Jane', 'Doe');
var student2 = new Student('John', 'Smith');
console.log(student1.firstName, student1.lastName);
console.log(student2.firstName, student2.lastName);
但是,如果你必须做它是你上面指定的方式:
var students = {};
function addNewStudent(firstName,lastName){
students[firstName+lastName] = 'Some random data';
}
addNewStudent('Hero','Man');
console.log(students);
用数组或对象文字(或“Map”或“Set”)做这件事情会容易得多。尽管使用变量(使用'eval')或多或少是可能的,这是不好的做法。 – Xufox
看起来你需要像这样的'new Student(firstName,lastName)'而不是。 – dfsq
你究竟想在这里完成什么?这种尝试对我来说没有多大意义。 – David