多维数组访问异常:为何BestAlbumsByGenre[0][1]返回字符'o'?
为什么访问多维数组元素返回单个字符?
你的问题出在没有正确创建多维数组结构,而是错误地将字符串当作数组来操作:
- 当你执行
BestAlbumsByGenre[0] = "Country"时,BestAlbumsByGenre[0]被赋值为字符串类型,而非数组。 - 在JavaScript中,字符串支持通过索引访问单个字符(索引从0开始),所以
BestAlbumsByGenre[0][1]实际是取字符串"Country"的第1位字符,也就是'o'——这就是你看到异常结果的原因。 - 你后续给
BestAlbumsByGenre[0][0]赋值的操作根本无效,因为JavaScript的字符串是不可变类型,无法通过索引修改字符内容。
修正后的代码
要实现你想要的多维数组结构,需要先给每个流派位置创建子数组,再填充内容:
let BestAlbumsByGenre = []; // 为Country流派创建子数组并填充内容 BestAlbumsByGenre[0] = []; BestAlbumsByGenre[0][0] = "Country"; BestAlbumsByGenre[0][1] = "Patsy Cline : Sentimentally Yours"; BestAlbumsByGenre[0][2] = "Hank Williams : I'm Blue Inside"; BestAlbumsByGenre[0][3] = "Johnny Cash : Live at Folsom Prison"; // 为Rock流派创建子数组并填充内容 BestAlbumsByGenre[1] = []; BestAlbumsByGenre[1][0] = "Rock"; BestAlbumsByGenre[1][1] = "T-Rex : Slider"; BestAlbumsByGenre[1][2] = "Nirvana : Nevermind"; BestAlbumsByGenre[1][3] = "Lou Reed : Transformer"; // 为Punk流派创建子数组并填充内容 BestAlbumsByGenre[2] = []; BestAlbumsByGenre[2][0] = "Punk"; BestAlbumsByGenre[2][1] = "Flipper : Generic"; BestAlbumsByGenre[2][2] = "The Dead Milkmen"; BestAlbumsByGenre[2][3] = "Patti Smith : Easter"; console.log(BestAlbumsByGenre[0][1]); // 输出:Patsy Cline : Sentimentally Yours
更推荐的结构:使用对象分类
如果你的需求是按流派分类存储专辑,用对象结构会更直观、易维护:
let BestAlbumsByGenre = { Country: [ "Johnny Cash : Live at Folsom Prison", "Patsy Cline : Sentimentally Yours", "Hank Williams : I'm Blue Inside" ], Rock: [ "T-Rex : Slider", "Nirvana : Nevermind", "Lou Reed : Transformer" ], Punk: [ "Flipper : Generic", "The Dead Milkmen", "Patti Smith : Easter" ] }; console.log(BestAlbumsByGenre.Country[1]); // 输出:Patsy Cline : Sentimentally Yours
内容的提问来源于stack exchange,提问作者Subhajit Khasnobish
相关产品推荐
相关产品推荐

