简体   繁体   中英

How to put variables inside a Json Array function in JS

I'm a beginner in Js and have a problem making a little program, I want to put the variables nome, document e Codigo, inside of the JSON array 'registros'

var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var registro = [{
        codigo: 0,
        nome: "",
        sexo: ""
    }];
    registro.push(codigo, nome, document);
}  

You need to do a little adjustment in the salvar() function. First, you can set each specific value of your "registro" var like this:

var registro = [{
    codigo: codigo, //value = 1
    nome: nome, //value = the innerText of document.getElementById("pNome")
    sexo: ""
}];

Then, you use the push() function to insert "registro" into your "registros" array. Here is the full updated code:

var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var registro = [{
        codigo: codigo,
        nome: nome,
        sexo: ""
    }];
    registros.push(registro);
}

Array in JS comes in property/ value structure, and from your code you are assigning the values to a different variable registro instead of registros.

Moreover, the registros variable is never user. To do this;

  1. Create your array variable (registros)
  2. Create a function (salvar)
  3. Create an object that will hold your values, here nome in object will create a property name "nome" with the value being the value in nome which is document.get...;
    var obj = { "nome": document.getElementById("pNome").innerText.
  4. Then push obj to array, registros
var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var obj = { nome, documento, caodigo}

    registros.push(obj);
}

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