-1

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
DigM
  • 509
  • 1
  • 4
  • 24
  • 2
    That's what [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is for – Andreas Mar 01 '19 at 15:35

1 Answers1

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>
ellipsis
  • 12,049
  • 2
  • 17
  • 33