Reputation: 6316
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>
Upvotes: 0
Views: 83
Reputation: 67207
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
.
Upvotes: 3
Reputation: 1074148
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
.)
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.
Upvotes: 4