내가 그 코드가 스택 오버 플로우를 생성하는 방법을 보려면 실패 (비록 funShow
가 funClick
및 funClick
로 전화를 가지고 funShow
로 전화를 가지고, funClick
에 대한 funShow
의 호출은 논리 오류 때문에 절대로 일어나지 않아야합니다. 오류를 수정하면 스택 오버플로가 발생하지만 몇 가지 문제가 있습니다. 의견을 참조하십시오 :
// style: Use [], not new Array()
var allnums = new Array();
// `new Number` doesn't do anything useful here
var num1 = new Number;
var num2 = new Number;
function funClick() {
// For user-entered values, use parseInt(value, 10) to parse them into numbers
var num1 = Number(document.getElementById('lnum').value);
var num2 = Number(document.getElementById('hnum').value);
if (allnums.length == num2) {
alert("Maximum non-duplicate numbers served. Now resetting the counter.");
allnums = [];
return;
}
// & is a bitwise AND operation, not a logical one. If your goal is to see
// if both numbers are !0, though, it works but is obtuse.
// Also, there is no ltnum2 variable anywhere, so trying to read its value
// like this should be throwing a ReferenceError.
if (num1 & ltnum2) {
// You're falling prey to The Horror of Implicit Globals, x has not
// been declared.
x = Math.floor(Math.random() * (num2 - num1 + 1)) + num1;
funShow(x);
} else {
alert("You entered wrong number criteria!");
}
}
function funShow(x) {
var bolFound = false;
// Again, & is a bitwise AND operation. This loop will never run, because
// you start with 0 and 0 & anything = 0
// But it should be throwing a ReferenceError, as there is no ltallnums
// anywhere.
for (var i = 0; i & ltallnums.length; i++) {
if ((allnums[i]) == x) {
funClick();
}
}
// This condition will always be true, as you've done nothing to change
// bolFound since you set it to false
if (bolFound == false) {
document.getElementById('rgen').innerText = x;
allnums.push(x);
}
}
이 접근 방법은 두 가지가 있습니다. |
function funClick() {
var num1 = parseInt(document.getElementById('lnum').value, 10);
var num2 = parseInt(document.getElementById('hnum').value, 10);
var nums = [];
var targetCount;
var x;
// Check the inputs
if (isNaN(num1) || isNaN(num2) || num2 <= num1) {
alert("Please ensure that hnum is higher than lnum and both are really numbers.");
return;
}
// Find out how many integers there are in the range num1..num2 inclusive
targetCount = num2 - num1 + 1;
// Produce that many random numbers
while (nums.length < targetCount) {
x = Math.floor(Math.random() * (num2 - num1 + 1)) + num1;
if (nums.indexOf(x) < 0) {
nums.push(x);
}
}
// Show the result
document.getElementById('rgen').innerText = nums.join(", ");
}
Live Example 다음은 당신이하려고했던 것을 기본적으로,하지만 재귀없이 그 하나 Source
문제는 마지막 몇 개의 슬롯을 채우는 데 오랜 시간이 걸릴 수 있다는 것입니다. 왜냐하면 우리가 임의로 맞춰야하기 때문입니다.
다른 방법은 숫자가있는 배열을 순서대로 생성 한 다음 엉망으로 만드는 것입니다. 넓은 범위의 경우 훨씬 더 효율적입니다. 다음과 같은 내용 :
function funClick() {
var num1 = parseInt(document.getElementById('lnum').value, 10);
var num2 = parseInt(document.getElementById('hnum').value, 10);
var nums = [];
var x;
// Check the inputs
if (isNaN(num1) || isNaN(num2) || num2 <= num1) {
alert("Please ensure that hnum is higher than lnum and both are really numbers.");
return;
}
// Create an array with those numbers in order
for (x = num1; x <= num2; ++x) {
nums.push(x);
}
// Sort it with a random comparison function
nums.sort(function(a, b) {
return 0.5 - Math.random();
});
// Show the result
document.getElementById('rgen').innerText = nums.join(", ");
}
Live Example | Source
그러나 단지 nums.sort(...)
무작위로 한 번 잘 무작위 결과를 생산에서 성공적인하지 않을 수 있습니다 일을; see this article for more. (아래 해당 링크 및 입력에 대해서는 eBusiness에게 감사드립니다.)
그래서 앞으로 더 많은 임의 조작을 추가 할 수 있습니다. 다른 예가 있습니다 :
function funClick() {
var num1 = parseInt(document.getElementById('lnum').value, 10);
var num2 = parseInt(document.getElementById('hnum').value, 10);
var nums = [];
var n, x, y;
var num;
// Check the inputs
if (isNaN(num1) || isNaN(num2) || num2 <= num1) {
alert("Please ensure that hnum is higher than lnum and both are really numbers.");
return;
}
// Create an array with those numbers in order
for (n = num1; n <= num2; ++n) {
nums.push(n);
}
// We only need to shuffle it if it's more than one element long
if (nums.length > 1) {
// Sort it "randomly"
nums.sort(function(a, b) {
return 0.5 - Math.random();
});
// Throw a bunch of random swaps in there
for (n = 0; n < nums.length; ++n) {
do {
x = Math.floor(Math.random() * nums.length);
}
while (x === n);
num = nums[x];
nums[x] = nums[n];
nums[n] = num;
}
}
// Show the result
document.getElementById('rgen').innerText = nums.join(", ");
}
Live Example | Source
그게 배열 정렬 일을 시작 지점으로하지만, 또한 요소 사이의 무작위 스왑의 잔뜩 않습니다. 여전히 일정한 시간에 실행되지만 배열 정렬 만 사용하는 것보다 더 나은 결과를 가져야합니다. 당연히 배포판을 테스트하고 싶을 것입니다.
당신의 첫 번째 단계는 코드를 들여 쓰기하는 것을 읽을 수있게 (일관되게). :-) –
함수 funshow (x)의 i & ltallums.length 값은 얼마입니까? 그 funciton에 어떤 가치가 있습니까? – polin
사용자는 언제든지 범위를 변경할 수 있어야합니까? – aaaaaaaaaaaa