javascript为什么word返回一个数组和word[0]未定义的javascript



我正在努力使我的网站成为双语网站。所以我想迭代我的JS对象翻译。我可以用以下代码迭代:

for (var word of translation) {
console.log(word);
}   

但后来我得到了这个:

从我使用这个代码的那一刻起,我就没有定义

for (var word of translation) {
console.log(word[0]);
}   

这是我的目标型号

translation = [ 
{ English : [ ["English" , "engels"], ["lblEng",""] ]}, 
{dutch : [["dutch" , "nederlands"], ["lblNl",""]]},
{ second : [["second","seconde"], ["sec",""]]},
{minut : [["minut", "minut"],["min",""]]},
{ hour : [["hour","uur"],["h",""]]},
{ day :[ ["day", "dag"],["d",""]]}, 
{ to : [["to", "naar"],["to",""]]},
{ from : [["from", "van"],["from",""]]}
]

for...of对数组中的值(即对象(进行交互。例如第一次迭代,word={ English : [ ["English" , "engels"], ["lblEng",""] ]}

因此,当您执行word[0]时,它是undefined,因为在word对象中没有0属性

for (var word of translation) {
console.log(word[0]);
}  

变量word将分配一个对象,如下所示:

{ English : [ ["English" , "engels"], ["lblEng",""] ]}

因此,word[0]返回undefined,因为对象没有属性0

也许,你真正想做的是:

const translation = [ 
{ English : [ ["English" , "engels"], ["lblEng",""] ]}, 
{dutch : [["dutch" , "nederlands"], ["lblNl",""]]},
{ second : [["second","seconde"], ["sec",""]]},
{minut : [["minut", "minut"],["min",""]]},
{ hour : [["hour","uur"],["h",""]]},
{ day :[ ["day", "dag"],["d",""]]}, 
{ to : [["to", "naar"],["to",""]]},
{ from : [["from", "van"],["from",""]]}
];

for (let word of translation) {
// get the keys and values and loop over them.
Object.entries(word).forEach(([lang, values]) => {
//values[0] returns the first index, so you can access it as follow:
let [first] = values;
console.log(lang, first);

});
}

感谢您的所有反应/回答。。。

当然,这确实帮助了我前进,如果需要一段时间才能做出回应,因为我正在对我的网络应用程序进行进一步的划分。

最新更新