从数组中打印多组数字

时间:2016-10-03 00:04:53

标签: javascript arrays



function numbersInBucket(setOfNumbers, numbersInArray) {
	var numbers = [];
	for (var i = numbersInArray; i > 0; i--){
		numbers.push(i);
	}
	numbers.sort(function(){
		return (Math.round(Math.random())-0.5);
		}
	);
	return numbers.slice(0, setOfNumbers).sort(function(a, b){return a - b});
}


function print(numbers){
	var html = "";
  	for (var i in numbers) {
    	html = html + '<li class="item">' + numbers[i] + '</li>';
  	}
  	document.getElementById("output").innerHTML = html;
} 

function rowOfNumbers(){
	for(var i = 0; i < 3; i++){
		print(numbersInBucket(5, 75));
	}
}
&#13;
.container {
   display: flex;
   flex-wrap: wrap;
   justify-content: center;
  }
  ul li {
    list-style: none;
    display: inline-flex;
    justify-content: center;
  }
  .item {
    border: 5px solid #E7F7F5;
    color: #E7F7F5;
    margin: 20px;  
    border-radius: 100px;
    font-size: 40px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 220%;
   justify-content: space-between;
  }
&#13;
<div class="container">
		<ul id="output"></ul>
</div>
<input class="button" type="button" value="click " id="reload" onclick="rowOfNumbers()">
&#13;
&#13;
&#13;

你好; 如何打印多组数字。例如, 3 12 23 33 44 2 5 13 22 36,12 12 27 29 44.使用我当前的代码,我可以按照我想要的方式输出一组数字。但我想要多个不同数字的套装。我尝试使用for循环而没有运气。这组数字必须在li标签内。有人可以请我指出正确的方向,我正在努力学习互动网络开发。

1 个答案:

答案 0 :(得分:0)

在这一行:document.getElementById("output").innerHTML = html;您将使用一组新元素替换元素的内部HTML。这意味着您在追加新生成的元素之前清空元素,因此它们的数量永远不会增加。

快速解决方案不是覆盖内部HTML,而是使用:document.getElementById("output").innerHTML += html;附加到它。

请参阅下面的概念验证示例:

function numbersInBucket(setOfNumbers, numbersInArray) {
	var numbers = [];
	for (var i = numbersInArray; i > 0; i--){
		numbers.push(i);
	}
	numbers.sort(function(){
		return (Math.round(Math.random())-0.5);
		}
	);
	return numbers.slice(0, setOfNumbers).sort(function(a, b){return a - b});
}


function print(numbers){
	var html = "";
  	for (var i in numbers) {
    	html = html + '<li class="item">' + numbers[i] + '</li>';
  	}
  	document.getElementById("output").innerHTML += html;
} 

function rowOfNumbers(){
	for(var i = 0; i < 3; i++){
		print(numbersInBucket(5, 75));
	}
}
.container {
   display: flex;
   flex-wrap: wrap;
   justify-content: center;
  }
  ul li {
    list-style: none;
    display: inline-flex;
    justify-content: center;
  }
  .item {
    border: 5px solid #E7F7F5;
    color: #E7F7F5;
    margin: 20px;  
    border-radius: 100px;
    font-size: 40px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 220%;
   justify-content: space-between;
  }
<div class="container">
		<ul id="output"></ul>
</div>
<input class="button" type="button" value="click " id="reload" onclick="rowOfNumbers()">