成对打印出数组元素

时间:2014-12-04 14:28:57

标签: javascript arrays

我想在输入以下4个名字后成对打印出来,如: asd配对dfs和fsd搭配到hkg ..

ASD ==== DFS
fsd ==== hkg

function shuffle(o) {
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
};

function myFunction() {
  var aname, i = 0,
    x, names = [],
    arname = [];
  x = prompt("Please enter number of list:");
  //var y = prompt("Enter digits:");
  while (i < x) {
    names[i] = prompt("Enter the names:", "");
    //names+=names;

    //document.getElementById("demo").innerHTML= "The names are " + names; 
    i++;
  }
  arname = shuffle(names);
  document.getElementById("demo").innerHTML = "The shufled array is " + arname;
}
<p>Click the button to shuffle.</p>

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>

1 个答案:

答案 0 :(得分:0)

function shuffle(o) {
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
};

function myFunction() {
  var aname, i = 0,
    x, names = [],
    arname = [];
  x = prompt("Please enter number of list:");
  while (i < x) {
    names[i] = prompt("Enter the names:", "");
    i++;
  }
  arname = shuffle(names);
  document.getElementById("demo").innerHTML = "The shuffled array is " + arname;
  for (var i=0;i<arname.length;i+=2) {
    document.getElementById("demo").innerHTML += '<br>'+arname[i];
    if ((i+1)<arname.length) document.getElementById("demo").innerHTML += "==="+arname[i+1];
  }
}
<p>Click the button to shuffle.</p>

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>