访问对象内的数组

Access array inside an object

本文关键字:数组 对象 访问      更新时间:2023-09-26
 var b = {
  maths:[12,23,45],
  physics:[12,23,45],
  chemistry:[12,23,45]
};

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

给定对象 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
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
}

很简单:

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

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

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

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

如果您需要访问数组中的数组,请尝试此操作。

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

在这里,我说的是进入最内部的数组并拉动 0 中的位置。