繁体   English   中英

如何在JavaScript中将对象添加到数组的末尾。 array.push接缝不适用于此处的对象

[英]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>

如果我将任何输入推送到数组,它都会起作用,但是当我推送对象时,它将无法正常工作

这段代码有一些问题:

  1. 您没有调用该函数。
  2. address_book.push正在运行,但是将对象转换为字符串会导致类似[object Object] 如果要表示对象,请使用alert(JSON.stringify(address_book))
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM