-2

If I have an array in Javascript :

var myArray = [];

myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });

Is there a way I do not have to define the var { id: 2, value: 3 } again and again?

Something which would allow me to create a variable and use it again like :

var something = { id: tempId, value: tempVal }

and then I can keep pushing new instances of something in the array?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Perhaps, but is there an equivalent of an object here? I am sorry I am new to JS. Like in Java it gives you a blueprint and you can create objects. – JavaJavaScript Dec 07 '15 at 00:39
  • yes I will put it as an answer – sinanspd Dec 07 '15 at 00:40
  • 2
    Javascript is not Java. Writing your code as if it was is a mistake. – Sverri M. Olsen Dec 07 '15 at 00:50
  • @Sverri I agree but I think OP is just trying to do Object Oriented Programming in JS which is a common thing – sinanspd Dec 07 '15 at 00:51
  • @SverriM.Olsen could you explain what you mean by this? – Eric Phillips Dec 07 '15 at 00:56
  • @EricPhillips Well, it would take a longer essay to explain the differences between the two languages, but it would boil down to the simple fact that they are just very different languages. Many languages are like this; Go, Ruby, C, Haskel, etc. You just do things in a certain way when using these languages. – Sverri M. Olsen Dec 07 '15 at 01:20

1 Answers1

0

So as I can understand from your comment you want a function that pushes an object to an array.

For javascript objects look here : http://www.w3schools.com/js/js_objects.asp Indeed, you have been creating classes all along.

function Something(id, value) {
                      this.id = id;
                      this.value = value
                 }

now when you are pushing this to an array you need to create an instance(an object)

such as

var something1 = new Something(1,2)
myArray.push(something1)

And if you want to access a field you will do

myArray[0]["id"]

see this question What techniques can be used to define a class in JavaScript, and what are their trade-offs?

Community
  • 1
  • 1
sinanspd
  • 2,589
  • 3
  • 19
  • 37