将文本框值转换为数组javascript

时间:2015-01-07 11:36:00

标签: javascript arrays

我需要从文本框中获取值并保存为数组。我的代码使用与数字结合的单词。我正在尝试将这些相关的单词分组并将其(每个单词)放入数组字段中。 我的代码没有分隔单词,只是将所有单词放在一个数组字段中。

代码:

  function a()
{
var text = prompt("Please enter your username"); 
var i;
var j ;
j = prompt("Please enter number of usersname ") ;
var text1 = "";

for(i = 1; i < j ; i++)
{
    text1+= text + i + " " ;
}
document.getElementById("txtFloodMsg").value = text1; // putting values in textbox 
}



function Nickname() {


var array =[];
var Guser;
Guser = document.getElementById("txtFloodMsg").value; //taking values from the textbox
array =  Guser.split(' '); // split it (here is the problem i guess)
var length = array.length;
var randome = array[Math.floor(Math.random() * array.length)];
var index = array.indexOf(randome);
document.getElementById("nick").value = randome;

    var r = confirm("Is It Okay To Continue ?");
    if ( r == true )
     {
        if(index>-1 && length > -1)
        {
           array.splice(index,1);
           document.getElementById("nick").value = randome;
           pass();
           checked();
        }
    else if( r != true )  
        {  
          randome = array[Math.floor(Math.random() * array.length)];
          document.getElementById("nick").value = randome;
          var s = confirm("Is It Okay To Continue ?");
          while ( s != true ) 
              {
               randome = array[Math.floor(Math.random() * array.length)];
               document.getElementById("nick").value = randome;
               s = confirm("Is It Okay To Continue ?");

                }

          pass();
          checked(); 
          }


      }


}

请帮助,谢谢:)

1 个答案:

答案 0 :(得分:0)

var myArray = [];
// ..

for(i = 1; i < j ; i++)
{
    myArray.push(text);
}

// ..

小提琴:http://jsfiddle.net/nek2Lmph/1