簡體   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