[英]array.push(object) not pushed at the end of the loop in javascript
[英]How do i add an Object to end of an array in javascript. array.push seams not working for object here
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>
如果我将任何输入推送到数组,它都会起作用,但是当我推送对象时,它将无法正常工作
这段代码有一些问题:
address_book.push
正在运行,但是将对象转换为字符串会导致类似[object Object]
。 如果要表示对象,请使用alert(JSON.stringify(address_book))
。 tempObj
未定义。 如下所示:
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>
说明 :
您没有创建任何要推入数组的对象。 首先,每次要将新对象推送到address_book
都需要创建tempObj
。 上面的代码将完全可以。
我会这样:
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.