Please look at the following code:
var arr = [];
var cc = function(){alert('xx');};
for(var i = 0; i<2; i ){
arr[i ] = function(){alert('yy');}
arr[i 10] = cc;
}
console.group('start')
console.group( '1')
console.info( arr[0] == arr[1]);
console.info( arr[0] === arr[1]);
console .info( arr[0].toString());
console.info( arr[1].toString());
console.groupEnd('1')
console.group('2')
console.info( arr[10] == arr[11]);
console.info( arr[10] === arr[11]);
console.info( arr[10].toString());
console.info( arr[11].toString());
console.group()
console.groupEnd(' Start');
The console running result in Firebug in Firefox is as follows:
Analysis: The loop of the fifth line of code begins. After the loop ends, the result of the arr array is:
arr[0] = function(){ alert('yy'); }
arr[1] = function(){ alert('yy'); }
arr[10] = cc
arr[11] = cc
As you can see, the console results, as shown above .
arr[0] is not equal to arr[1]
But arr[10] is equal to arr[11] because it refers to the previously defined variable.
In fact, the function function(){alert('yy');} is being redefined during the loop.
The contents of the toString output of arr[0] and arr[1] are the same. However, the two methods are independent and occupy their own memory. Therefore, in order to save memory, the function can be defined outside the loop.
The prerequisite for a function to be defined outside a loop is that the function does not accept variables that change within the loop.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn