-1

I am looking for a way to separate objects from an array, having only the index avaiable. I have something like this:

     var hello= [];
     for (var i=0; incr.lenght>0; i++;)
     {

        hello+= originalarray[incr[i]].item;

       }

Array: 0: item0 1: item1 2: item2 3: item3

Having this: hello+= originalarray[incr[0,2,3]].item;

I get this: item0item2item3

The "item" comes from another array, this is a small part of my code, but hopefully it's enough to explain my problem. When I create an alert(hello); what I get is a list of item like this: item0item1item2item3. What I am looking for is a way to separate them. But I need to use the localStorage as well, and I was thinking of creating a different key for every value of the index. Hope it makes sense, I am a new user. Thank you very much!

1 Answers1

0

First of all, the for loop you have in your question has several issues:

  • It has three ;, while the syntax only allows two. You need to remove the final one

  • It has a condition that is never true, because lenght has a spelling mistake. If you correct it it will always be true (infinite loop):

    incr.length>0
    

    This should be:

    i < incr.length
    

Then the main issue is that you apply a string operator (+=) to concatenate the items, and so hello is no longer an array, but a string:

    hello+= originalarray[incr[i]].item;

Instead you should use push:

    hello.push(originalarray[incr[i]].item);

In order to store hello in localStorage you should not try to make a key for each item and store each separately. Instead use JSON.stringify (for writing) and JSON.parse (for reading) as explained in this Q&A.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Please read again, I wrote it in a negative way: *"It has a condition that is never true"*. Also note I wrote *"If you correct it"* to make the other claim. – trincot Nov 18 '18 at 10:04