2013-06-18 72 views
0

什麼最容易理解解決走出值如下:提取值

Bill, Smith, 32 
Sarah, Lord, 28 

我只得到了這麼遠:

HTML

<a href="#" onclick="displayEmployees();">displayEmployees</a>

的Javascript

function displayEmployees() { 
var employees = new Array(); 
employees['firstName'] = new Array('Bill','Sarah','Elizabeth','David','Robert'); 
employees['lastName'] = new Array('Smith','Lord','Crayford','Clark','Robinson'); 
employees['age'] = new Array('32','28','20','54','18'); 
for(x in employees) { 
    var value = employees[x] 
    document.write(value + "<br />"); 
} 

回答

1

你可以這樣做

var value; 
for(x in employees['firstName']){ 
    value = employees['firstName'][x]+', ' 
      +employees['lastName'][x]+', ' 
      +employees['age'][x]; 

    document.write(value + "<br />"); 
} 

更好的方法是創建其他方式員工陣列,這樣

employees = [{'firstName':'Bill','lastName':'Smith','age':32}, 
      {'firstName':'Sarah','lastName':'Lord','age':28},...]; 

var value; 
for(x in employees){ 
    value = employees[x].join(', '); 
    document.write(value + "<br />"); 
} 
+0

難道你不認爲這個答案看起來像現有答案的混合 – bugwheels94

+0

@Ankit難道你不認爲我投票的問題與投票無關嗎?答案肯定比接受的答案更清晰,甚至沒有更好的格式; 2.第二個答案(Esailija)實際上並沒有回答這個問題? – Chris

+0

@ChrisDemetriad讓我客氣清楚你一兩件事,我沒有downvote你隊友 – bugwheels94

2
var array = [ 
    ["Bill", "Smith", "32"], 
    ["Sarah", "Lord", "28"], 
    ["Elizabeth", "Crayford", "20"], 
    ["David", "Clark", "54"], 
    ["Robert", "Robinson", "18"] 
]; 
for (var i = 0, len = array.length; i < len; ++i) { 
    document.write(array[i].join(", ") + "<br>"); 
} 
2
function displayEmployees() { 
var employees = new Array(); 
employees['firstName'] = new Array('Will','Sarah','Elizabeth','David','Robert'); 
employees['lastName'] = new Array('Smith','Lord','Crayford','Clark','Pattinson'); 
employees['age'] = new Array('32','28','20','54','18'); 
for(var i=0;i<employees['firstName'].length;i++)    //can be employees['lastName']or employee['age'] too 
{ 
    document.write(employees['firstName'][i]+','+employees['lastName'][i]+','+employees['age'][i]+'<br />');} 
}