-
Problems with using random function with while loop
I have a while loop that I need to shuffle the order of my array. This was initially an AS2 code and am trying to convert this over but have come across with an error I don't understand so hoping someone may know what it means. My while loop code is:
Code:
var randomArray = shuffle(orderArray);
function shuffle(toShuffle) { // shuffles an array
var newMcOrder = new Array();
while (!end) {
var myRandom = Math.random * toShuffle.length;
var selected = toShuffle[myRandom];
toShuffle.splice(myRandom, 1);
newMcOrder.push(selected);
if (toShuffle.length == 0) end = true;
}
return newMcOrder;
}
The problem with the above is the line: var myRandom = Math.random * toShuffle.length;
This is given me the following:
1067: Implicit coercion of a value of type Function to an unrelated type Number.
Thanks
Eddie
-
assuming myRandom is a number, there shouldnt be any problem with that line.
it is however difficult to understand your code since you have not given each variable a type. it might not be required for flash, but is makes everything a lot easier to understand and in some cases helps the compiler understand too.
in your code for example, try declaring the types and show us the code again, with some of the code before it as well:
actionscript Code:
var randomArray:Array = shuffle(orderArray); function shuffle(toShuffle:Array) { // shuffles an array var newMcOrder:Array = new Array(); while (!end) { var myRandom:Number = Math.random * toShuffle.length; var selected:Object = toShuffle[myRandom]; toShuffle.splice(myRandom, 1); newMcOrder.push(selected); if (toShuffle.length == 0) end = true; } return newMcOrder; }
-
Try writing it like this
Actionscript Code:
var myRandom = Math.random() * toShuffle.length;
random is a function of the Math class, and without adding parantheses, the compiler will assume you are trying to access a property named 'random' within the Math class, which doesn't exist.
-
igorski got the fix right, but there is in fact a random property in Math. It's the function. Without the parentheses you are trying to multiply the function by a Number, which results in the error you saw
Implicit coercion of a value of type Function to an unrelated type Number.
-
I stand corrected, as my explanation didn't exactly give you information why you got that exact error. Thanks to flax
-
Thanks for your fix, error no more.... cheers
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|