我是從JavaScript開始的。我試圖做一個小程序,對文本文檔中找到的答案數進行統計。如何測試一個id是否存在於一個關聯數組中
的情況是這樣的:每個問題都有一個ID,e.g 8000001
和W
如果答案是好還是R
如果回答不好,e.g爲用戶的答案是8000001W
。我有很多用戶對同一個ID有這麼多問題。每個問題我想得到很多好的答案。例如:800001有W: 24 and "R": 5
。
我有答案分成id
爲8000001
和ans
爲W
或R
。我想創建一個關聯表來獲得question[id]=["W": 0, "R": 0]
。但我在這方面阻止。我試過這段代碼:
var tab = [];
tab[0] = [];
tab[0] = ['8000001W', '8000002W', '8000003W', '8000004R', '8000005W', '8000006R'];
tab[1] = [];
tab[1] = ['8000001R', '8000002W', '8000003R', '8000004W', '8000005R', '8000006W'];
var question = [];
var id;
for (var i=0;i<tab.length;i++) {
document.write("<dl><dt>tableau n° "+i+"<\/dt>");
for (var propriete in tab[i]) {
id = tab[i][propriete].slice(0,7);
var ans = tab[i][propriete].slice(7,8);
question[id] = [];
if(question[id]){
incrementResp.call(rep, ans);
}else{
var rep = initResp(ans);
question[id] = rep;
}
}
document.write("<\/dl>");
}
function incrementResp(type){
this.this++;
}
function initResp(t){
rep = [];
rep.W = (t=='W'?1:0);
rep.R = (t=='R'?1:0);
}
'
原諒它是爲了計算器。這不是在我的代碼 – rodolphe
不知道你在問什麼,但嘗試使用通用對象{},你可以檢查一個屬性是否存在'if(tab ['id']){ /*做些什麼*/ } ' – user1094553