Home > Web Front-end > JS Tutorial > JavaScript strings are copied and passed by reference, and compared by value. Introduction and application_javascript skills

JavaScript strings are copied and passed by reference, and compared by value. Introduction and application_javascript skills

WBOY
Release: 2016-05-16 17:44:58
Original
1033 people have browsed it
By-value and by-reference comparisons
Numbers and Boolean types (true and false) are copied, passed, and compared by value. When copying or passing by value, a space is allocated in computer memory and the original value is copied into it. Then, even if you change the original value, it will not affect the copied value (and vice versa), because the two values ​​are independent entities.

Objects, arrays, and functions are copied, passed, and compared by reference. When copying or passing by address, a pointer to the original item is created and then used as if it were copied. If you subsequently change the original item, both the original item and the copied item will be changed (and vice versa). There is actually only one entity; the "copy" is not really a copy, but just another reference to the data.

When comparing by reference, for the comparison to be successful, both variables must refer to the exact same entity. For example, two different Array objects will compare as unequal even if they contain the same elements. For the comparison to be successful, one of the variables must be a reference to the other. To check whether two arrays contain the same elements, compare the results of the toString() method.

Finally, strings are copied and passed by reference, but compared by value. Note that if there are two String objects (created with new String("something")), they are compared by reference, but if one or both are string values, they are compared by value.

Strings are copied and passed by reference, but compared by value. Note that if there are two String objects (created with new String("something")), they are compared by reference, but if one or both are string values, they are compared by value.
Copy code The code is as follows:

var str1="aa";
var str2 =new String("aa");
var str3=str2;
function test(p){
var str4=p;
console.log(str4===str2);
}
console.log(str1===str2); //false
console.log(str3===str2); //true
test(str1);//false
test(str2);//true
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template