ajax不适用于数组

时间:2012-10-15 15:21:45

标签: javascript ajax

我正在尝试使用ajax将文本文件中的信息加载到数组中,并且我正在使用此代码:

function loadWords(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "dico/francais.html");
    xhr.onreadystatechange = function(){
        if(xhr.readyState == xhr.DONE && xhr.status == 200){
            dico = xhr.responseText.split("\n");
            for(var i=0; i<wordsNBR; i++){
                var x = Math.floor(Math.random()*dico.length);
                words[i] = dico[x];
            }
        }
    }
    xhr.send(null);
}

它有问题,但当我试图改变时

for(var i=0; i<wordsNBR; i++){
                var x = Math.floor(Math.random()*dico.length);
                words[i] = dico[x];
            }

for(var i=0; i<wordsNBR; i++){
                var x = Math.floor(Math.random()*dico.length);
                words.push(dico.splice(x,1));
            }

它不起作用任何人都知道为什么?

1 个答案:

答案 0 :(得分:1)

dico.splice(x,1)更改数组并返回已删除的元素。这可能与x&lt; dico.length因为它在dico数组中随机抽取一个字。

所以我想你的第一个错误只是你使用了错误的变量。

另一个错误是splice返回一个数组而不仅仅是一个元素。如果您想要返回的元素,则需要dico.splice(x,1)[0]

这样做:

var x = Math.floor(Math.random()*dico.length); // takes an index in what is left in dico
words.push(dico.splice(x,1)[0]); // removes the word and add it to words