0

I want to create C# like list in JavaScript. In C# we can say List<string> ListName = new List<string>();

And then it allows you to add N number of members to the list by using add method.

ListName.add("1");
ListName.add("2");
..
..
ListName.add("N");

How can I create similar list in JavaScript.

I was thinking of using array but it forces me to specify the size.

var a = new Array(5); 
a = [0, 0, 0, 0, 0]; 
var a = new Array(0, 0, 0, 0, 0); 
2
  • i just want to know something you managed to learn C# and having trouble using the basic in javascript? you might need a bacic javascript tutorial Commented Mar 27, 2014 at 12:51
  • @Phoenix: Very valid point. But I declared array like this var a = [] and was able to push the data. But while accessing I was not able to retrieve the value. And I got confused. It turned out that I added a semicolon in front of for loop and values were printed as undefined. Commented Mar 27, 2014 at 13:12

3 Answers 3

7
var someArray = [];
someArray .push(elem);

that's all.

P.S. There are also lots of interesting things. So, I advise you to check MDN documentation

Sign up to request clarification or add additional context in comments.

7 Comments

How do I retrieve this value using for loop?
you can retrieve this by using plain for loop either array's foreach. for (var i = 0; i < someArray.length; i++) {console.log(someArray[i]) }
I created this fiddle jsfiddle.net/RhUc9 . What is wrong with it? I am not able to access by array[i]. This is the whole reason I posted this question
Actually I don't see any fiddle in this topic.
That's ok. :) Good luck with JS. It's a really powerful language. I picked JS half year ago, and I really like it. (a java developer)
|
0

Nope in javascript also you can declare a array like

    var yourarr=[];

this will create a dynamic array and then you can add value in it like

      yourarr.push(value1);
      yourarr.push(value2);
       .
       .
     yourarr.push(valueN);

And also pop them out as yourarr.pop();

this will pop out last value from the array and you can also use indexing to retrieve value and perform on them.

And it dynamic no need to give any Size.

Comments

0
var listName = [];
listName.push("1");
listName.push("2");
..
..
listName.push("N");         // At this step listName = ["1", "2", ... "N"]

Then you can loop through array items like:

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

2 Comments

How do I retrieve the value?? var a = []; a.push(1); a.push(2); for(i =0; i < a.length; i++); { console.log(a.length); console.log(a[i]); }
You have already written how you can retrieve items from the array.

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.