0

I have an array with string values. I want to add additional text before or after each value in the array. How can I do this?

From what I have seen I am guessing it will be something like:

$.each(array, function() {
   // something here
});

Everything I have tried doesn't seem to be working.

2
  • What what did you try? Commented Sep 11, 2011 at 18:17
  • If you look at the documentation for the function you're trying to use, you'll see that the handler conveniently receives both the array index and value of the element under iteration. Always read the documentation when you're not sure about a function that you're trying to use. Commented Sep 11, 2011 at 18:18

2 Answers 2

3

I think you can use plain JavaScript, that runs a little bit faster.

for(i=0;i<array.length;i++) {
 array[i] = 'some text ' + array[i] + ' some other text';
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I think in this case it's easier not to use jQuery, since jQuery returns the values too (and you're actually only looking for the numeric keys).
Yup. Worked beautifully. I was overcomplicating it. :)
@Tim: Well, not quite. You do use the values!
3

You're on the right track. Try:

$.each(array, function(i, v){
   array[i] = array[i] + 'hello';
});

You could also use map:

var newArray = $.map(array, function(v, i) {
   return v + 'hello';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.