I’m still working on a program and I have a problem. The code is here:
function Calculate(){
var elev = [];
var inputs = document.getElementsByName("txt");
for(i=0; i<inputs.length; i++) {
elev[i] = {
"Value": inputs[i].value,
"Used": false
};
}
for(j=0; j<=10; j++) {
var r = Math.floor(Math.random() * 20);
if (elev[r].Used) { //1st number
for(var a=0; a<=21; a++) {
if (!elev[a].Used) {
elev[r].Value = elev[a].Value;
break;
}
else {continue; }
}
}
...
}
}
elev[r].used = true;
doument.write(elev[r].Value);
...
}
}
First of all, I have 22 imports to the var inputs[i].value (later elev[i]) in my HTML document. I want it to use all of the ‘elev’ arrays once, but I see (in my document.write as I clipped out here) it uses some of them twice and some of them isn’t even used. How can I fix that?
Problem solved by using the Fisher-Yates shuffle
Let me point out several problems with your script
First of all this section
You are assigning the value to the array but it is of type
String. String does not get the properties.The following code will work
But if you do so
attempt to use
str.SomePropwill always returnundefinedThe code
if (elev[r].used)will always be evaluated to false (because0, empty string,false,nullandundefinedbehaves as false inifoperator in JavaScript)So I suggest you to refactor your code into
And finally the block
if (elev[aa].used = false)will not throw exception, but this is a error.Consider the following snipped
It will work because you are assigning the value false to the
someValvariable and this instruction is evaluated to true. Some the alert with messageThat's wierdwill appear. Furthermore, you’ll notice that thesomeVal‘s value isfalse.This snipped uses the equality operator which will be evaluated to false and the first alert will not work out. However there is a problem too. A stylistic one. Never check the value for false, especially in JavaScript.
The correct snippet must look like this.
P.S.
You get the variable
aafrom nowhere. Where does it come from? It must be undefined. What did you want?Concatinated values of two numbers? The sum of them?
EDIT:
Just a few notices.
1) Use
for (var a = 0; a < someConstant; a++)syntax. Don’t forget to add var keyword.2) Use proper indention, i.e.
3) Don’t use
emptyelse block.