2017-09-06 105 views
0

我是社区新手,最近发布了这个问题,但我的描述并不够详细,无法获得我期待的回复。抱歉。但是,谢谢大家,他们提供了帮助。到目前为止,我可以创建一个数组,其中随机绘制一个元素,并通过单击按钮将其呈现在屏幕上。然后将该元素从阵列中删除完美!但是,我只在屏幕上显示当前正在切片的元素。我想要做的是将每个单独的元素显示在屏幕上,因为它是随机拼接的,所以我最终得到屏幕上的所有元素和一个空数组。我非常不成功地尝试使用循环。对不起,我的初始文章缺乏清晰度,并提前感谢您提供了额外的帮助。在屏幕上随机显示所有数组元素

function RandomDraw(){ 
    var ri = Math.floor(Math.random() * myArray.length); 
    var rs = myArray.splice(ri, 1); 
    document.getElementById("showSplice").textContent = rs; 
    document.getElementById("showArrayList").innerHTML = myArray; 
} 
+0

myArray中的项目是什么? – jANVI

回答

2

使用innerHTML + =而不是用textContent标出现有的值。请参阅this code pen

function RandomDraw(){ 
    var ri = Math.floor(Math.random() * myArray.length); 
    var rs = myArray.splice(ri, 1); 
    document.getElementById("showSplice").innerHTML += rs; 
    document.getElementById("showArrayList").innerHTML = myArray; 
} 
+0

太棒了!非常感谢。我并不期待它看起来那么容易。感谢您的教训。 - 很好 – Don199

+0

很高兴我能帮到你。不要忘记接受最能帮助你解决问题的答案。 –

1

您可以追加文本内容而不是覆盖它。

function RandomDraw(){ 
    var ri = Math.floor(Math.random() * myArray.length); 
    var rs = myArray.splice(ri, 1); 
    document.getElementById("showSplice").textContent += ' ' + rs; 
    document.getElementById("showArrayList").innerHTML = myArray; 
} 
+0

Sooo酷!这是完美的。我期待着许多代码行来实现这一点。我有很多要学习的。感谢您的教育。 - 唐 – Don199

2

目前尚不清楚,因为你说你想使用一个循环,你是否仍然希望这一个按钮的点击,所以我实现了一个setTimeout模仿什么,我想你想实现:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

// Grab the elements outside of the function so you don't grab 
// them each iteration 
var showSplice = document.getElementById("showSplice"); 
var showArrayList = document.getElementById("showArrayList"); 

function loop(arr) { 

    // If there are still elements in the array 
    if (arr.length) { 
    var ri = Math.floor(Math.random() * arr.length); 
    var rs = arr.splice(ri, 1); 

    // If the array still has elements append the spliced element and 
    // a comma to the textContent, otherwise just the spliced element 
    showSplice.textContent += arr.length ? rs + ', ' : rs; 
    showArrayList.innerHTML = arr; 

    // Send the spliced array to loop again (1/2 second loop) 
    setTimeout(loop, 500, arr); 
    } 
} 

// Call loop with the array 
loop(arr); 

DEMO

+0

不是我正在寻找。但是,感谢你的教训。这对我来说更加重要。 -Don – Don199

1

const myArray = [1, 2, 3, 4, 5]; 
 

 
document.getElementById("showArrayList").innerHTML = myArray.join(', '); 
 

 
function RandomDraw(){ 
 
    const ri = Math.floor(Math.random() * myArray.length); 
 
    const rs = myArray.splice(ri, 1); 
 
    const showSpliceElement = document.getElementById("showSplice"); 
 
    const splicedElements = showSpliceElement.innerHTML; 
 
    showSpliceElement.innerHTML += 
 
     splicedElements && rs.length 
 
     ? `, ${rs}` 
 
     : rs; 
 
    document.getElementById("showArrayList").innerHTML = myArray.join(', '); 
 
}
Splice: <span id="showSplice"></span><br> 
 
Array: <span id="showArrayList"></span><br> 
 
<button onclick="RandomDraw()">Go</button>