Why is it taking my function and making it not a function anymore?
I have a function that returns a random number from 1-10. When I use it in my other function it works once, but then it starts having an error that it's not a function. This isn't the exact code, just an example code that's similar. It produces an error saying "TypeError: Property 'ran' of object [object DOMWindow] is not a 开发者_高级运维function" Why is it doing this?
Thanks alot
var buffer = [];
function ran() {
return Math.round(Math.random()*10);
};
function test(){
var size = 6;
for (i=0; i<=size;i++) {
var num = ran();
if (num === 2 || num === 3){
buffer.push(num);
};
};
};
Your code is fine, but from the error it looks like you're assigning some value to an implied global variable called ran
somewhere else in your code.
var buffer = [];
function ran() {
return Math.round(Math.random()*10);
};
function test() {
var size = 6;
for (i=0; i<=size;i++) {
var num = ran();
if (num === 2 || num === 3){
buffer.push(num);
};
};
};
// ... somewhere else:
function someOtherFunction() {
ran = 5; // This will break your run() function when
// someOtherFunction() is called.
}
If this is the case, make sure to limit the scope of your variables to the function in which they are declared by using the var
keyword:
// ... somewhere else:
function someOtherFunction() {
var ran = 5; // This will limit the scope of ran and will
// not conflict with the run() function.
}
精彩评论