console.log() shows the changed value of a variable before the value actually changes

后端 未结 7 2009
无人共我
无人共我 2020-11-22 02:09

This bit of code I understand. We make a copy of A and call it C. When A is changed C stays the same

var A = 1;
var C = A;
console.log(C); // 1
A++;
console.         


        
7条回答
  •  自闭症患者
    2020-11-22 02:54

    Arrays are objects. Variables refer to objects. Thus an assignment in the second case copied the reference (an address) to the array from "A" into "C". After that, both variables refer to the same single object (the array).

    Primitive values like numbers are completely copied from one variable to another in simple assignments like yours. The "A++;" statement assigns a new value to "A".

    To say it another way: the value of a variable may be either a primitive value (a number, a boolean, null, or a string), or it may be a reference to an object. The case of string primitives is a little weird, because they're more like objects than primitive (scalar) values, but they're immutable so it's OK to pretend they're just like numbers.

提交回复
热议问题