最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access array inside an object - Stack Overflow

programmeradmin7浏览0评论
 var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

I want to access array in object b. ie, maths, physics, chemistry . This may be a simple question but i am learning....Thanks

 var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

I want to access array in object b. ie, maths, physics, chemistry . This may be a simple question but i am learning....Thanks

Share Improve this question edited Mar 19, 2015 at 9:23 Wenbing Li 13k1 gold badge31 silver badges42 bronze badges asked Mar 19, 2015 at 8:53 SauryaSaurya 511 gold badge1 silver badge6 bronze badges 2
  • 1 There has to be a canonical duplicate for this. – ohmu Commented Mar 19, 2015 at 12:47
  • possible duplicate of JavaScript property access: dot notation vs. brackets? – ohmu Commented Mar 19, 2015 at 12:53
Add a ment  | 

6 Answers 6

Reset to default 6

Given the arrays in the object b (note that you have a syntax error in the code you provided)

var b = {
  maths: [12, 23, 45],
  physics: [12, 23, 45],
  chemistry: [12, 23, 45]
};

maths, physics, and chemistry are called properties of the object stored in variable b

You can access property of an object using the dot notation:

b.maths[0]; //get first item array stored in property maths of object b

Another way to access a property of an object is:

b['maths'][0]; //get first item array stored in property maths of object b
var b = {
    maths:[12,23,45],
    physics:[12,23,45],
    chemistry:[12,23,45]
};

console.log(b.maths);
// or
console.log(b["maths"]);
// and
console.log(b.maths[0]); // first array item
var b = {
    maths:[12,23,45],
    physics:[12,23,45],
    chemistry:[12,23,45]
};

// using loops you can do like
for(var i=0;i<b.maths.length;i++){
      console.log(b.maths[i]);//will give all the elements
}

there are simple:

b = {
      maths:[12,23,45],
      physics:[12,23,45],
      chemistry:[12,23,45]
    };

b.maths[1] // second element of maths
b.physics
b.chemistry

You need to set the variable b like this :

var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

Then you can access your arrays inside b by using b.maths, b.physics and b.chemistry.

If you ever need to access an array inside of an array, try this.

var array2 = ["Bannana", ["Apple", ["Orange"], "Blueberries"]];
array2[1, 1, 0];
console.log(array2[1][1][0]);

Here I am saying to go inside the inner most array and pull what is in place 0.

发布评论

评论列表(0)

  1. 暂无评论