javascript raw values and object reference instance analysis

  • 2020-06-03 05:41:50
  • OfStack

This article gives an example of how javascript raw values and object references work. Share to everybody for everybody reference. The specific analysis is as follows:

In one sentence: The original value is immutable, while the object reference is mutable.

The primitive values in js (undefined, null, booleans, Numbers, and strings) are essentially different from objects (including arrays and functions). The original value is immutable, and no method can change 1 original value. For a string, all the methods in the string appear to return a modified string, but in fact return a new string value:


var str="hello world";
s.toUpperCase();
s;     // Still the same 

Comparisons of raw values are comparisons of values: they only want to wait if their values are equal.

Objects differ from the original values. First, they are mutable. Secondly, the comparison of objects is not a comparison of values; Comparisons of objects are referential comparisons: they want to wait if and only if they reference the same base object.
To compare two separate objects or arrays, you must compare their attributes or elements, as follows:


function equ_arrays(a,b){
  if(a.length != b.lenght) return false;
  for(var i=0;i<a.length;i++)
    if(a[i] !== b[i]) return false;
  return true;
}

I hope this article has been helpful for your javascript programming.


Related articles: