【问题标题】:Access array inside an object访问对象内的数组
【发布时间】:2015-03-19 08:53:06
【问题描述】:
 var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

我想访问对象 b 中的数组。即,数学、物理、化学。 这可能是一个简单的问题,但我正在学习....谢谢

【问题讨论】:

标签: javascript arrays


【解决方案1】:

给定对象 b 中的数组(请注意,您提供的代码中有语法错误)

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

mathsphysicschemistry 被称为存储在变量 b 中的对象的 properties

您可以使用点符号访问对象的属性:

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

访问对象属性的另一种方法是:

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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:
      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
      }
      

      【讨论】:

        【解决方案4】:

        有简单的:

        b = {
              maths:[12,23,45],
              physics:[12,23,45],
              chemistry:[12,23,45]
            };
        
        b.maths[1] // second element of maths
        b.physics
        b.chemistry
        

        【讨论】:

          【解决方案5】:

          你需要像这样设置变量 b:

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

          然后您可以使用 b.maths、b.physics 和 b.chemistry 访问 b 中的数组。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-11-22
            • 1970-01-01
            • 2020-10-23
            • 2019-07-29
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多