从函数参数创建变量

时间:2015-09-06 18:55:19

标签: javascript

我想从这些函数参数创建新变量。怎么办呢?

function addNewStudent(firstName,lastName){
var firstName+lastName = new Student();
}

addNewStudent('Hero','Man');

错误消息: 未捕获的SyntaxError:意外的标记+

2 个答案:

答案 0 :(得分:0)

我会推荐上面的@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);

http://jsfiddle.net/8m7351fq/

但是如果你必须按照上面指定的方式进行:

var students = {};

function addNewStudent(firstName,lastName){
    students[firstName+lastName] = 'Some random data';
}

addNewStudent('Hero','Man');
console.log(students);

http://jsfiddle.net/em1ngm2t/1/

答案 1 :(得分:0)

制作动态变量需要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

使用Map(仅支持ES6):

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来获取整个列表。是不是更方便和明智?