let address_book = [];
function myFunction() {
let contact_name, contact_email, contact_phone;
contact_name = document.getElementById("contact_name").value;
contact_email = document.getElementById("contact_email").value;
contact_phone = document.getElementById("contact_phone").value;
address_book.push({
name: contact_name,
email: contact_email,
phone: contact_phone
})
alert(address_book)
console.log(tempObj)
}
</script>
如果我将任何输入推送到数组,但是当我按下对象时
,则无效答案 0 :(得分:0)
此代码存在一些问题:
address_book.push
正在运行,但将对象转换为字符串会产生类似[object Object]
的内容。如果您想要对象的表示,请使用alert(JSON.stringify(address_book))
。tempObj
未定义。答案 1 :(得分:0)
如下所示:
let address_book = [];
function myFunction() {
var tempObj = {};
tempObj.contact_name = document.getElementById("contact_name").value;
tempObj.contact_email = document.getElementById("contact_email").value;
tempObj.contact_phone = document.getElementById("contact_phone").value;
address_book.push(tempObj)
console.log(tempObj)
}
alert(address_book)
</script>
解释:
您没有创建任何要推入阵列的对象。首先,每次要将新对象推送到tempObj
时,都需要创建address_book
。上面的代码完全没问题。
答案 2 :(得分:0)
我这样做:
var address_book = [];
var i = 0;
function myFunction() {
let contact_name, contact_email, contact_phone;
contact_name = document.getElementById("contact_name").value;
contact_email = document.getElementById("contact_email").value;
contact_phone = document.getElementById("contact_phone").value;
var user = {
name: contact_name,
email: contact_email,
phone: contact_phone
}
address_book[i] = user;
i++;
alert(address_book)
}