如何在javascript中添加一个Object到数组的末尾。 array.push接缝在这里不适用于对象

时间:2018-04-08 10:15:57

标签: javascript arrays object

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>

如果我将任何输入推送到数组,但是当我按下对象时

,则无效

3 个答案:

答案 0 :(得分:0)

此代码存在一些问题:

  1. 您没有调用此功能。
  2. address_book.push正在运行,但将对象转换为字符串会产生类似[object Object]的内容。如果您想要对象的表示,请使用alert(JSON.stringify(address_book))
  3. 之类的内容
  4. 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)
    }