2

I have a field named tags. The input to this field can be any number of strings,depending on the user.And I need to store those strings in separate variable names. I tried something like this:

var tagsInputArray = ["a", "b"......n elements];
var tagsLength = tagsInputArray.length;
var count = 0;
for (count; count < tagsLength; count++) {
    var tags[count] = tagsInputArray[count];
}

This is not working. How can I do it in jQuery?

4
  • What does that have to do with jQuery? Commented May 26, 2015 at 6:23
  • @Amit Im working in jQuery. So i tagged it jQuery. Is there any other tags that I can use for generic doubts like this?. Im new to stackOverFlow. Commented May 26, 2015 at 6:26
  • 1
    @ArunMohan I need to store those strings in separate variable names What do you mean by this? Give an example Commented May 26, 2015 at 6:28
  • @Tushar Say i have 4 elements in tagsArray like this tagsArray = ["india","pakisthan","china","bangladesh"] I need to get store each element in a variable like this: var country1 = "india"; var country2 = "pakisthan"; var country3 = "china"; var country4 = "bangladesh"; Commented May 26, 2015 at 6:29

2 Answers 2

2

length is not defined anywhere you probably need to use tagsLength in loop

for(count;count<tagsLength ;count++){

You also have error for var tags[count] = tagsInputArray[count]; as this is wrong syntax for declaring array. Removing the var key word would remove the error and your code would work.

Live Demo

var tagsInputArray = ["a", "b"];
var tagsLength = tagsInputArray.length;
var count = 0;
var tags = [];
for (count; count < tagsLength; count++)
     tags[count] = tagsInputArray[count];

for (count = 0; count < tags.length; count++)
  alert(tags[count]);

I would also recommend to use .push to add array element to other array, see this demo.

tags.push(tagsInputArray[count]);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var tagsInputArray = ["a", "b"......n elements];

var tags = [];
for (var count = 0; count < tagsInputArray.length; count++) {
    tags[count] = tagsInputArray[count];
}

console.log(tags);

The problem with your code is that

var tags[count] = tagsInputArray[count];

inside for loop, tags is undefined and you are adding elements inside it. I've solved it by defining tags as array before for loop and then inserted elements inside it.

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.