0

I am working on the following code. How can I print out three url address like:

www.example/app
www.example/map
www.example/tap

var comp = ["app", "map", "tap"];

$(comp).each(function() {
  var url = 'www.example/' + comp;
  console.log(url);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128

2 Answers2

4

You don't use $().each, you use $.each on an array. Or, with any JavaScript engine updated since 2009, you use the array's own forEach.

Using $.each:

$.each(comp, function(index, entry) {
    var url = 'www.example/' + entry;
    console.log(url);
});

Note that the entry is the second argument, not the first. (It's also this.)

Using forEach (spec | MDN):

comp.forEach(function(entry) {
    var url = 'www.example/' + entry;
    console.log(url);
});

Note that the entry is the first argument. (You can also use a second and third argument: The second is the index, the third is the array itself.)

This answer has a comprehensive list of the ways you can loop through the contents of arrays and array-like things.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

You can simply use Array.prototype.forEach,

comp.forEach(function(url) {
  console.log('www.example/' + url);
});

There is no need to use jQuery $.each() at this context. By the way you are using $().each, that is different and that can be used to traverse Jquery element collection not an array.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • You probably want to change the name of the argument, or remove the `var`. It happens that it will work as is, because the `var` will be a no-op, but... – T.J. Crowder Mar 20 '16 at 10:59
  • @TJ Anyway that would over ride it right? I did a small test in the console. `function test(url){ var url = "helo" + url; console.log(url) } test("test");` – Rajaprabhu Aravindasamy Mar 20 '16 at 11:04
  • Right, that's why I said it works in this particular case, the `var` is essentially ignored. – T.J. Crowder Mar 20 '16 at 11:10