简体   繁体   中英

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>

it works if i push any of the input to the array, but not working when i push the object

This code has some problems:

  1. You aren't calling the function.
  2. address_book.push is working, but transforming objects to strings result in something like [object Object] . If you want a representation of the object use something like alert(JSON.stringify(address_book)) .
  3. tempObj is not defined.

Do it like below:

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>

Explanation :

You were not creating any object to push into the array. First you need to create a tempObj every time you want to push a new object into your address_book . Above code will perfectly fine.

I'd do it this way:

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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