2015-09-06 66 views
-3
創建一個變量

我想從這些函數參數中創建新變量。如何做呢?從函數參數

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

addNewStudent('Hero','Man'); 

錯誤消息: 未捕獲的SyntaxError:意外的令牌+

+1

用數組或對象文字(或「Map」或「Set」)做這件事情會容易得多。儘管使用變量(使用'eval')或多或少是可能的,這是不好的做法。 – Xufox

+0

看起來你需要像這樣的'new Student(firstName,lastName)'而不是。 – dfsq

+0

你究竟想在這裏完成什麼?這種嘗試對我來說沒有多大意義。 – David

回答

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。這不是更方便,更合理嗎?

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/