简体   繁体   中英

How can I push an array to another array

Please see my code below, and how can I add array to TA array.

 var TA = [ { fname: "Carl", lname: "Buck", id: 12890, spec: "Programming", selected: true }, { fname: "Jim", lname: "Tomic", id: 13000, spec: "Database", selected: true }, { fname: "Dave", lname: "Jackson", id: 12000, spec: "Networking", selected: false }, { fname: "Jack", lname: "Bryant", id: 12345, spec: "Testing", selected: true }, { fname: "Peter", lname: "Pan", id: 11111, spec: "Testing", selected: false } ]; localStorage.TA = JSON.stringify(TA); var TA2 = JSON.parse(localStorage.TA); function create() { var fname = document.getElementById("fname").value; var lname = document.getElementById("lname").value; var id = document.getElementById("id").value; var spec = document.getElementById("program").value; var check = document.getElementById("check").value; TA2= TA2.concat(["fname"]: fname, ["lname]:lname, ["id"]:id, ["spec"]: spec, ["selected"]: check]) } var output = ""; for (var i = 0; i < TA2.length; i++) { for (var property in TA2[i]) { output += property + ": " + TA2[i][property] + "\r\n"; } } alert(output);

I am guessing you want to push(replicate) all data from one array to another array, the following code does the work,

this.array2 = [...this.array1]

Using concat works fine but the parameter you send should be a proper object. In your code snippet there are syntax errors (for example "lname is missing the closing double-quote). I've simplified your object to just have fname and id and cleaned up your code to show it can work in the snippet below. I also just used a local tmp variable instead of localStorage and console.log instead of alert so the snippet can run here.

Note that saying { fname } is a short form of writing { fname: fname } which makes it more readable and works because the variable name is the key name.

Also if you just want to add one new entry to the end, you can use the push function instead of concat . It works, but concat can take an array or multiple values as parameters to allow you to merge 2 arrays together and isn't really what you are doing.

 var TA = [ { fname: "Carl", id: 12890 }, { fname: "Jim", id: 13000 }, ]; var tmp = JSON.stringify(TA); var TA2 = JSON.parse(tmp); function create() { var fname = "Mary"; var id = 314159; TA2 = TA2.concat({ fname, id }); } create(); console.log(TA2);
If you run this you'll see that the new entry is concatenated.

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