简体   繁体   中英

Javascript Variables as Object Pointers

I have a question out of curiosity. So I looked into how JS handles variable assignment and I get it. How does variable assignment work in JavaScript?

But the same principle doesn't seem to exhibit itself in the following code I am working on:

var temp = playlist1[0];
playlist1[0] = playlist1[1];
playlist1[1] = temp;

I know this is a standard way to swap array elements. But if temp is pointing at playlist1[0] , and playlist1[0] 's contents are changed to playlist1[1] 's then how come I don't end up with two playlist1[1] values in a row?

Not only variables are object pointers. All values (that are not primitives) are object pointers. So temp is an object pointer. playlist1 is a object pointer to an array object whose elements are object pointers. eg playlist1[0] is an object pointer, playlist1[1] is an object pointer, etc.

But if temp is pointing at playlist1[0]

This doesn't make sense. temp is an object pointer. It points to an object. playlist1[0] is not an object; it's an object pointer. temp = playlist1[0]; makes the object pointer temp point to the same object as object pointer playlist1[0] .

If you know C, it is equivalent to something like this:

Object *playlist1[10];

Object *temp = playlist1[0];
playlist1[0] = playlist1[1];
playlist1[1] = temp;

This is consistent with the answer in the referenced question: You are just changing which object the variable points to - not the data it used to point to. Meaning temp is unaffected by the move to have playlist1[1] point to playlist1[2]. Temp retains the original value it pointed to when playlis1[1] and temp both pointed to it. Only playlist1[1] is updated

Because those are still references to elements in the array and not the elements themselves. So in the line:

playlist[1]=playlist[2]

You are not changing anything about temp. Contrast that with something like (assuming array elements were objects):

playlist[1].x=playlist[2].x

That is actually assigning the value of the object in the array, and if temp pointed to playlist[1], then temp.x would equal playlist[2].x

say we have obj={l1:{l2:[1,2]},} and we want to address obj.l1.l2[1] using an array of levels like arr=["l1","l2",1] then :

Object.defineProperty(Object.prototype,'point',{
    value:function(arr){
        var rez=this;
        for(var s in arr){
            rez=rez[arr[s]];
            if(rez === undefined) return undefined;
        }
        return rez;
    }
});

So after defining "point" method (which is not enumerable to mess up everithing) we can use

obj.point(arr)

to get value 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM