如何正确分割字符串数组这是另一个问题

How do I correctly split an array of strings of is it another issue?

本文关键字:另一个 问题 数组 何正确 分割 字符串      更新时间:2023-09-26

我正试图从字符串数组中访问一个随机元素,就像这里的其他例子一样。我正在使用拉斐尔.js和区域[j]下面返回拉斐尔对象的数组-因此。data(id)。这似乎没有问题,但是在下面的评论中概述的theCountyNames将所有字符串作为一个长字符串返回。我猜这就是为什么randCounty返回一个随机字母,但是当我尝试在循环中添加逗号(+",")并根据这个问题使用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];
}
然而,这并没有被优化,因为你可以预先设置数组的长度,你甚至可以完全跳过循环,
function pickRandCounty(){
    var j = Math.floor(Math.random() * regions.length);
    return regions[j].data('id');
}

错误似乎就在这一行。

theCountyNames = regions[j].data('id'); //wrong
theCountyNames.push(regions[j].data('id')); //right

第二个错误

document.write(theCountyNames); //it will keep on appending the string in the DOM
document.write("<br>" + theCountyNames);//right