I am trying to learning the Google Drive Realtime Api and have a question about the CollaborativeList. I am new to JavaScript.
var mylist = model.createList();
mylist.push("apple");
mylist.push("orange");
mylist.push("banana");
mylist.push("grape");
var result = mylist.indexOf("grape");
and the result is 3, which makes sense. Now, if I create a list that is made up of objects:
var mylist = model.createList();
var apple = {"color": "red","time": "0"};
mylist.push(apple);
var orange = {"color": "orange","time": "1"};
mylist.push(orange);
var banana = {"color": "yellow","time": "2"};
mylist.push(banana);
var grape = {"color": "purple","time": "3"};
mylist.push(grape);
var result = mylist.indexOf(grape);
Now the result is -1. There must be something I don't understand. What am I doing wrong?
The Collaborative List is not idential to
Array#push
. It copies and wrap the object, and doesn't refer to it by its reference.When you use the the collaborative list
.indexOf()
like thismylist.indexOf(grape);
you are trying to find an object with the same referece ofgrape
, since none exists, it returns-1
.Example
In the example we push an object to a collaborative list, and to a JS array. We mutate the original object, and
console.log()
the item from the collaborative list, and from the array. As you can see the object from the collaborative list didn't change (a copy), while the one in the array did (a reference).