2

Hello I have a var called numbers which is a string of number broken by a , I need to use each of these to do something with. Can anyone help me fill in the missing part:

var numbers = 1313,1314,1252,1244,1223,34,123,1,245;

(FOR Each number of numbers set AS numbersSingle)
     var numbersSingle = 1313;
    $(".notification").remove("#" + messageSingle);

I hope this makes sense, if anyone needs anymore information please let me know, thanks all!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    each element has specific id hence no need to use class specifier, Simply remove the item by its id. – Braj Jul 27 '15 at 09:21
  • do you want to split the variable on "," and get all the numbers? I din't understand what you want to convey by using the for each loop here. – Rajan Goswami Jul 27 '15 at 09:23

5 Answers5

1

You can do something like this

var numbers = ("1313,1314,1252,1244,1223,34,123,1,245").split(",");

for (var a = 0; a < numbers.length; a++) {
  $(".notification").remove("#"+numbers[a]);
}
slashsharp
  • 2,823
  • 2
  • 19
  • 26
1
var numArray = numbers.split(',');

for (var x = 0; x < numArray.length; x ++) {
    console.log(numArray[x]);
}

Here is a JSFiddle - open the console to see output.

The bit you're missing is the split() function that converts a string to an array based on a separator.

You can use other loops on the array if you prefer - there's some more detail here.

Community
  • 1
  • 1
Toni Leigh
  • 4,830
  • 3
  • 22
  • 36
1

Assuming the var is a string.

var numberArray = numbers.split(',') //This will return an array with earch element split by a comma.

iterate through the array using

numberArray.each(function(e){
  console.log(e); //do what ever you want for each value.
})
Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
1

You don't need to loop here. You can amend the string to form a valid selector with each id separated by a string, eg: #1313,#1314... etc, and then remove them all in a single operation. Try this

var numbers = "1313,1314,1252,1244,1223,34,123,1,245";
$('.notification').remove('#' + numbers.replace(',', ',#'));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

You can use split and $.each from jquery

 $(document).ready(function() {

    var numbers = "1313,1314,1252,1244,1223,34,123,1,245";
    var numbersArr = numbers.split(",");
     $.each(numbersArr,function(key, value) {
          console.log(value);
     });
   });

where value is each value from your numbers

ref split

ref $.each

Community
  • 1
  • 1
Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29