我想使用html元素显示关联数组的值,但我似乎无法获取值,因为它总是输出undefine。
我的代码是这样的:用户将注册数据,注册的数据将存储在一个对象中,并将使用一个键"用户名"访问它。当用户搜索用户名时,必须使用html元素显示值。
这是我的代码。谢谢
var storage = [];
function viewUserArray()
{
var zName = document.getElementById('checkArray').value;
var html = "<h1> Username Details </h1>";
var anotherhtml = "<p>";
var uName;
var fName;
var elmail;
var pword;
var b_day;
var g_nder;
for (key in storage)
{
if(key === zName)
{
uName = storage[key].uName;
fName = storage[key].fName;
elmail = storage[key].elmail;
pword = storage[key].pword;
b_day = storage[key].b_day;
g_nder = storage[key].g_nder;
html += "<p>Username : " + uName + "</p>";
html += "<p>Full Name : " + fName + "</p>";
html += "<p>Email : " + elmail + "</p>";
html += "<p>Password : " + pword + "</p>";
html += "<p>Age : " + b_day + "</p>";
html += "<p>Gender : " + g_nder + "</p>";
}
document.getElementById("target").innerHTML = html;
}
}
function setValuesArray()
{
var uName = document.getElementById('username').value;
var fName = document.getElementById('fullName').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = getAge();
var g_nder = document.getElementById('gender').value;
storage[uName] = (storage[uName]||[]).concat({//add user to storage[uName]
"Username" : uName,
"Full Name" : fName,
"Email" : elmail,
"Password" : pword,
"Age" : b_day,
"Gender" : g_nder
});
}
答案 0 :(得分:0)
与其他答案完全相同:
var storage = {};
function viewUserArray()
{
var zName = document.getElementById('checkArray').value;
var html = "<h1> Username Details </h1>";
var anotherhtml = "<p>";
var uName;
var fName;
var elmail;
var pword;
var b_day;
var g_nder;
if(!storage[zName]){
console.log("doesn't exist");
return;
}
uName = storage[zName].uName;
fName = storage[zName].fName;
elmail = storage[zName].elmail;
pword = storage[zName].pword;
b_day = storage[zName].b_day;
g_nder = storage[zName].g_nder;
html += "<p>Username : " + uName + "</p>";
html += "<p>Full Name : " + fName + "</p>";
html += "<p>Email : " + elmail + "</p>";
html += "<p>Password : " + pword + "</p>";
html += "<p>Age : " + b_day + "</p>";
html += "<p>Gender : " + g_nder + "</p>";
document.getElementById("target").innerHTML = html;
}
}
function setValuesArray()
{
var uName = document.getElementById('username').value;
var fName = document.getElementById('fullName').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = getAge();
var g_nder = document.getElementById('gender').value;
//I assume there is only one uName so update the uName if it exist and create it if it doesn't
// storage[uName] = (storage[uName]||[]).concat({//add user to storage[uName]
storage[uName] = {//update or add
uName,
fName,
elmail,
pword,
b_day,
g_nder
};
}
您也不会始终在保存它们的相同键下获取值:
您将用户保存为:"Username" : uName,
,但神奇地希望获得以下值:storage[zName].uName
在“用户名”键下保存一个值,然后尝试使用键“uName”获取值