繁体   English   中英

js数组关联:indexOf不是函数

[英]js array associative: indexOf is not a function

我不知道我的代码有什么问题。 请问你能帮帮我吗? 此功能将使用数组翻译单词。 完整的任务是:

以以下方式将小的双语词典作为Javascript对象表示为{“ merry”:“ god”,“ christmas”:“ jul”,“ and”:“ och”,“ happy”:gott“,” new“:” nytt”,“ year”:“ĺr”},并使用它将您的圣诞贺卡从英语翻译为瑞典语。

 function translateText(){ var translate=[], i= 0,text, word, text2=''; translate = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ĺr"}; text = document.getElementById('text').value; word = text.split(" "); for (i;i<word.length; i++){ if (translate.indexOf(word)!==-1) { text2 += translate[word] + " "; }else{ text2 += word + " "; } } document.getElementById('boxEight').innerHTML = text2; } 

它不起作用,因为您使用的是对象而不是数组 ,尽管对象的使用方式类似于数组。

要检查对象是否包含值,可以使用hasOwnProperty

if (translate.hasOwnProperty(word)) {
  ...
}

in

if (word in translate) {
  ...
}

或者,如果您只关心它具有一个“真实的”值(不是0falsenullundefinedNaN或空字符串),或者只是一种老式的访问方式。

if (translate[word]) {
  ...
}

我不确定,但是我认为这可能是您将转换数组转换为带有以下行的对象的事实:

translate = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ĺr"};

尝试将花括号{}更改为方括号[]

您要翻译一个对象,而不是数组,所以首先:

translate = [{"merry":"god"}, {"christmas":"jul"}, {"and":"och"}, {"happy":"gott"}, {"new":"nytt"}, {"year":"ĺr"}];

下,的indexOf是用于得到一个字或字符的索引中的字符串的方法参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM