web123456

JS advanced type storage method—including heap/stack analysis

// Example 1: var arr1 = []; var arr2 = []; // 1) When comparing, the result is false // 2) Because the variable in the stack stores the address, not its value, the storage addresses of the two arrays are compared at this time, and the addresses are of course different, so it is false console.log( arr1 === arr2 ); // Example 2: Shared Address => Advanced types can share one address with multiple variables: create 1 array, and many variables use the address of this array var arr3 = []; // 1) arr3 and arr4 share the address of the same array, but this operation is actually not good, and some unexpected structures will be generated. At this time, the array corresponding to the arr4 address is operated, and arr3 is viewing the same array var arr4 = arr3; // 2) Add data behind arr4[arr4.length] = "hello world"; // 3) The output is successful, and "hello world" is also added to arr3 console.log( arr3 ); // 4) Note: // Try to avoid the use of such same address variables at the same level, and only use this address assignment when the scope is different // For example, in the example above, you can directly access arr3, so there is no need to add an additional variable arr4 and then perform operations // Example 3: Shared address in special cases function push( arr , data ){ // 1) Added a piece of data to the end of the array through the push function return arr[ arr.length ] = data; } var arr5 = []; // 2) When calling the function, the actual parameter must be data. If the actual parameter position is a variable, it means variable access => At this time, arr5 is the address of the array, and "hello world5" is the corresponding data push( arr5 , "hello world5" ); console.log( arr5 ); var arr6 = []; // 3) The same as above here push( arr6 , "Hello World") console.log( arr6 ); // 4) Explanation: By calling the push function, you can add a piece of data to the last position of the current array, and the shared address is used here