我正在尝试根据其他示例here on SO从字符串数组访问随机元素。我正在使用Raphael.js,下面的region [j]返回一个Raphael对象数组-因此是.data(id)。这似乎可以,但是如下面的注释中所述,CountyNames将所有字符串作为一个长字符串返回。我猜这就是randCounty返回单个随机字母的原因,但是当我尝试在循环(+“,”)中添加逗号并按照this question使用split时,我仍然得到一个随机单个字母。也许我执行不正确,或者是另一个问题?谢谢。

 function pickRandCounty(){
var theCountyNames = new Array();
for (var j = 0; j < regions.length; j++) {
theCountyNames = regions[j].data('id');
document.write(theCountyNames);//THIS GIVES ME THE COMPLETE LIST OF ITEMS IN THE ARRAY BUT ALL AS ONE STRING
//document.write("<hr>");
 }
//var randCounty = theCountyNames[Math.floor(Math.random() * theCountyNames.length)];
//document.write(randCounty);//THIS JUST RETURNS ONE RANDOM LETTER??
}

最佳答案

使用Array.prototype.push将新项目附加到数组。

function pickRandCounty(){
    var theCountyNames = [],
        j;
    for (j = 0; j < regions.length; ++j) {
        theCountyNames.push(regions[j].data('id'));
    }
    j = Math.floor(Math.random() * regions.length);
    return theCountyNames[j];
}


但是,由于您可以预先设置Array的长度,甚至可以完全跳过循环,因此并没有进行优化。

function pickRandCounty(){
    var j = Math.floor(Math.random() * regions.length);
    return regions[j].data('id');
}

关于javascript - 如何正确分割字符串数组,这是另一个问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32027139/

10-09 18:21
查看更多