Add to value arrays [duplicate]

40
March 02, 2019, at 09:40 AM

This question already has an answer here:

  • How to append something to an array? 30 answers

I want to split a string by commas and then add them to an array. So far I have the following:

var temp = new Array();
temp = element.innerHTML.split(",");
for (i = 0; i < temp.length; i++) {
  var data = [{
    type: 'image',
    src: '/resources/'+ temp[i],
  },
}];

However, at the moment, if I run this it will reset the value of data everytime. How could I change it so that for each of my array values it adds to the data array?

Answer 1

Try this. You are creating the array on every iteration thats why the data is getting reset. Use push() to put data in array

var temp = new Array(); 
element=document.querySelector('div') 
temp = element.innerHTML.split(","); 
var data=[]; 
for (i=0;i<temp.length;i++){ 
   data.push({ 
    type: 'image', 
    src:'/resources/'+ temp[i], 
}) 
  } 
  console.log(data)
<div>1,2,3,4,5,6,7,8,9</div>

READ ALSO
node.js request stuck in middleware function (authentication)?

node.js request stuck in middleware function (authentication)?

I am building a nodejs server to handle logins and actions in my iOS app

36
Problem with reading api giving json data

Problem with reading api giving json data

i would like to program myself a webpage that displays some data from companiesI already found a API that displays different values, which someone could choose

42
Can&#39;t delete my first item in shopping basket

Can't delete my first item in shopping basket

Currently doing my computing science assignment and I've chosen to make an online shop, I've used a tutorial to make the shopping basket and everything is working except I can only delete every item except the first one added to my cartI'd really appreciate...

40
I want to pick out one column of the DataFrame but the result is automatically ordered by values

I want to pick out one column of the DataFrame but the result is automatically ordered by values

I just need one column of my dateframe, but in the original orderWhen I take it off, it is sorted by the values, and I can't understand why

28