0

I've been away from javascript/jquery fro few years and now it feels like I can't find the simplest things. I have this object stations like:

var station = {
  stationId;
  stationName;
}

Now if I want an array of stations, can't I do like:

var stationList = new station [sizeofarray];

Looks like I can't and didnot find any straight forward answers on search.

1
  • Your object is improperly formatted, the semicolons would cause an error. It might be useful to brush up on Javascript Objects Commented Aug 4, 2017 at 22:54

2 Answers 2

1
var stationList = [{stationId:1, stationName:''}];

this create an array with one object inside.

If want push anoder object just. push to array like this

stationList.push({stationId:2, stationName:'otherName'});
Sign up to request clarification or add additional context in comments.

Comments

1

If you need to put only one object inside the array, you can simply do the following:

var station = {
  stationId: 'id',
  stationName: 'name'
}
var stationList = [station];
console.log(stationList);

If you need to put more than one element, or the array is not empty, you can push the object to the end of the array (it doesn't make sense if you need to put only one object to the array):

var station = {
  stationId: 'id',
  stationName: 'name'
}
var stationList = [];

stationList.push(station);
console.log(stationList);

Or to the start of the array:

var station = {
  stationId: 'id',
  stationName: 'name'
}
var stationList = [];

stationList.unshift(station);
console.log(stationList);

7 Comments

So when I create it, I can't specify a size? To make it a certain size, I need to push that many times using a loop?
No, you can specify the size, may be only in typescript and such typed languages, and i'm not sure about it. And yes, if you need to put more than one element to the array, better use a loop.
You can do new Array(length); to get an array of a specific size, Array constructor reference. But this just sets the Array's length property, the actual slots do not exist, ie initialized with undefined value, till you put something in them.
@PatrickEvans, and we can't exceed this number by pushing new elements?
too much barring. Oh Well. Thanks everyone.
|

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.