NodeJS 我尝试访问此多维数组的元素,并得到如下奇怪的结果:“o”,“u”

uxh89sit  于 2023-01-08  发布在  Node.js
关注(0)|答案(2)|浏览(127)
let BestAlbumsByGenre = [];
    BestAlbumsByGenre [0]  = "Country";
    BestAlbumsByGenre [0][0] = "Johnny Cash : Live at Folsom Prison";
    BestAlbumsByGenre [0][1] = "Patsy Cline : Sentimentally Yours";
    BestAlbumsByGenre [0][2] = "Hank Williams : I'm Blue Inside";
    BestAlbumsByGenre [1] = "Rock";
    BestAlbumsByGenre [1][0] = "T-Rex : Slider";
    BestAlbumsByGenre [1][1] = "Nirvana : Nevermind";
    BestAlbumsByGenre [1][2] = "Lou Reed : Transformer";
    BestAlbumsByGenre [2] = "Punk";
    BestAlbumsByGenre [2][0] = "Flipper : Generic";
    BestAlbumsByGenre [2][1] = "The Dead Milkmen";
    BestAlbumsByGenre [2][2] = "Patti Smith : Easter";
    
  console.log(BestAlbumsByGenre[0][1]);

这是我的准则。
如果我想访问BestAlbumsByGenre[0][1],它应该返回"Patsy Cline:深情属于你";但是它返回的是字符'o',也许它返回的是第0个元素的第2个字符,字符串"Country",但是如果是这样的话为什么呢?

c7rzv4ha

c7rzv4ha1#

BestAlbumsByGenre [0] = "Country"(将字符串设置为数组中的第0项)之后,BestAlbumsByGenre [0][0] = "Johnny Cash : Live at Folsom Prison"不再有效。BestAlbumsByGenre[0][1]返回该字符串中的第一个字符。
考虑不同的数据结构,例如:

BestAlbumsByGenre[0] = {Genre: "Country", Albums: []};
BestAlbumsByGenre[0].Albums[0] = "Johnny Cash : Live at Folsom Prison";
qhhrdooz

qhhrdooz2#

我认为你根本不理解javascript中的多维数组结构,这个例子能让它们的结构更清晰吗?

let BestAlbumsByGenre = [];
BestAlbumsByGenre[0] = [
  "Country", // 0 0
  [ // 0 1
    "Johnny Cash : Live at Folsom Prison", // 0 1 0
    "Patsy Cline : Sentimentally Yours", // 0 1 1
    "Hank Williams : I'm Blue Inside" // 0 1 2
  ]
]; //etc...

console.log(BestAlbumsByGenre[0][0]);  //Country
console.log(BestAlbumsByGenre[0][1][1]); //Patsy Cline : Sentimentally Yours

相关问题