簡體   English   中英

帶有Java字符串數組中的鍵的關聯數組

[英]Associative Array with keys from an Array of Strings in Javascript

我試圖在Javascript中形成一個單詞列表,其中每個單詞都是字典中的一個鍵,並且值是true。 我的程序接受一個單詞,然后檢查該單詞在列表中是否為有效單詞。 單詞列表存儲在文本文件中,其中的單詞用換行符分隔。 我將這些單詞掃描為一個字符串並將其拆分,以獲得包含所有單詞的字符串數組。 現在,我無法從該數組形成關聯數組。 這是我的代碼:

var dict={};
var words;
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }


xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
words=xmlhttp.responseText.split("\n");
for ( var i = 0; i < words.length; i++ ) {
       dict[words[i]] = true; //This Section of Code not working
}
}
 }


xmlhttp.open("GET","twl06.txt",true);
xmlhttp.send();
}
function check(str)
{
if(dict[str])
    alert("Correct");
else
    alert("Incorrect");
}

在對代碼進行了大量調整之后,我發現以某種方式未形成關聯數組。

這是我完整的html / JS代碼的鏈接: https : //pastebin.com/2jwMcBfA

當您拆分時,我會以為您拆分\\r\\n不僅會\\n留下\\r尾隨

除非words [i]是整數,否則您不能將其用作另一個數組的索引(JavaScript沒有關聯數組)。

最好的解決方法是執行dict [words.indexOf(i)] /(edited)/或其他將word [i]轉換為整數的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM