Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array inside a JavaScript Object?

Tags:

javascript

I've tried looking to see if this is possible, but I can't find my answer.

I'm trying to get the following to work:

var defaults = {  'background-color': '#000',  color: '#fff',  weekdays: {['sun','mon','tue','wed','thu','fri','sat']} }; 

It just gives an error, and I've tried using ({...}) and [{...}] I'd like to be able to access the weekdays using something like:

defaults.weekdays[0]; 

is this possible?

like image 792
Mottie Avatar asked Dec 01 '09 21:12

Mottie


People also ask

Can you put an array inside an object in JavaScript?

You can use Array inside object JavaScript. Not even Array anything inside JavaScript objects, including other objects, functions, etc can define. Array is an object, and you can have an object as a property of another object.

Can an object have arrays?

Each variable or object in an array is called an element. Unlike stricter languages, such as Java, you can store a mixture of data types in a single array. For example, you could have array with the following four elements: an integer, a window object, a string and a button object.

How do you store an array in an object?

Syntax: Class_Name obj[ ]= new Class_Name[Array_Length]; For example, if you have a class Student, and we want to declare and instantiate an array of Student objects with two objects/object references then it will be written as: Student[ ] studentObjects = new Student[2];

How do you access an array within an object?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.


2 Answers

Kill the braces.

var defaults = {  backgroundcolor: '#000',  color: '#fff',  weekdays: ['sun','mon','tue','wed','thu','fri','sat'] }; 
like image 135
Stefan Kendall Avatar answered Sep 19 '22 19:09

Stefan Kendall


// define var foo = {   bar: ['foo', 'bar', 'baz'] };  // access foo.bar[2]; // will give you 'baz' 
like image 23
Eimantas Avatar answered Sep 21 '22 19:09

Eimantas