What is the difference between these arrays? - javascript

var foo = {}
var bar = new Array();
var another = [];
Also, is it possible to add to foo like so:
foo['obj'] = new Date();

var foo = {};
foo is an object literal.
var bar = new Array();
bar is an array initialized via the Array constructor.
var another = [];
another is an array literal. Creating new arrays through literals is more efficient than doing so through the Array constructor: http://jsperf.com/new-array And it’s also much easier to type ;) I’d recommend using array literals wherever possible.
Also, is it possible to add in foo like so: foo['obj'] = new Date();
Yes. That will add a property obj to foo with the value of new Date(). It’s equivalent to foo.obj = new Date();.

foo is an object, not an array.
bar and another are arrays.
if you give foo['obj'] = new Date();, obj will become a property of foo.

var foo = {}
This is an object, not an array.
var bar = new Array();
This is array but avoid new keyword with arrays.
var another = [];
This is correct way of initializing array.
Also, is it possible to add in foo like so: foo['obj'] = new Date();
There is no associative array in JS. You can instead do:
var foo = {};
var foo['obj'] = new Date();

bar and another are the same, but:
var foo = {};
foo is not an array rather an object
foo['obj'] = new Date(); //same as
foo.obj = new Date();
the advantage of f['obj'] is that you can use non-valid identifier characters ex:
foo['test-me'] // is valid
foo.test-me //not valid

var foo = {} is for object referal,
foo = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales}
while
var bar = new Array(); is used to create new empty array.
But var another = []; can be used to assign any array empty values as well as creates empty array.
I think for date you can use like foo[1] = new Date();

Related

Array insertion JavaScript

I have a use case as follows
var myObject1 = new myObject();
and myObject should have an array which will store all the objects created of this myObject
Example:-
if create an object such as
var xyz = new myObject();
myObject.all[0] == xyz
is there any way where - when I create an object & I can push it into an array which is in the definition of same object.
You can create a property directly on the constructor function, to get the myObject.all[0] == xyz behaviour mentioned in the question. Add each object to the array from within the constructor:
function MyObject() {
MyObject.all.push(this);
// any other initialisation tasks here
}
MyObject.all = [];
var obj1 = new MyObject();
var obj2 = new MyObject();
// to access the array use MyObject.all:
console.log(MyObject.all[1] === obj2); // true
Alternatively, you can add an array to the object prototype, but still add new objects to that array from within the constructor:
function MyObject() {
this.all.push(this);
// any other initialisation tasks here
}
MyObject.prototype.all = [];
var obj1 = new MyObject();
var obj2 = new MyObject();
// to access the array:
console.log(obj1.all);
// or
console.log(MyObject.prototype.all);
console.log(obj1.all[1] === obj2); // true
(Note: in both examples, I've spelled MyObject with a capital "M", because it is a JS convention for functions intended as constructors to be capitalised. This isn't mandatory.)
Maybe something like this?
function MyObject(name){
if (!O.prototype.instances) O.prototype.instances = [];
O.prototype.instances.push(name);
}
var a = MyObject('a');
var b = MyObject('b');
console.log(MyObject.prototype.instances)

Convert JSON to JavaScript Object of Type X

I know all about JSON.stringify or JSON.parse in the sense that one serializes an object and one deserializes the string back into an object. This is great!
However, I have the following situation:
var i = new MyMagicalObject();
var oi = JSON.parse(JSON.stringify(i));
console.log(i.numFields()); // this is fine
console.log(oi.numFields()); // this throws since Object has no method 'numFields'
Basically, I'd like to treat oi as an instance of "MyMagicalObject" since that's what it is.
I'm sure there's some magic about setting the prototype on oi or something, but I'm fairly new to JavaScript. Any help would be appreciated.
You can't "store" JavaScript functions in JSON strings.
The only data types that can be stored in JSON are:
Number
String
Boolean
Array
Object
null
(source)
Anything that isn't one of those types, gets ignored:
function Test(){
this.foo = function(){
return 'bar';
}
this.theAnswer = '42';
}
var t = new Test();
alert(t.foo());
alert(JSON.stringify(t))
Your problem could be easily solved by redesigning your MyMagicalObject class. Here is an example of JSON-friendly class:
function MyMagicalObject(props) {
this.props = props || {};
}
MyMagicalObject.prototype.get = function(key) {
return this.props[key];
};
MyMagicalObject.prototype.set = function(key, val) {
this.props[key] = val;
return this;
};
MyMagicalObject.prototype.toJSON = function() {
return this.props;
};
MyMagicalObject.prototype.numFields = function() {
return Object.keys(this.props).length;
};
This realization follows two rules:
It's constructor accepts JSON representation as a first argument.
It provides toJSON method to tell JS engine how to convert its instance to JSON.
Check the following example:
var obj = new MyMagicalObject();
obj.set('foo', 42).set('bar', 'baz');
alert(obj.numFields()); // 2
var str = JSON.stringify(obj);
var obj2 = new MyMagicalObject(JSON.parse(str));
alert(obj2.numFields()); // 2
You can create a new MyMagicalObject() and then overwrite its properties with the one from oi.
var t = new MyMagicalObject();
for(var k in oi) t[k]=oi[k];
That should do the trick. If you have a more complex object (with more than 1 dimension), search for a copy function that deep copies all properties.
Add oi.prototype = MyMagicalObject.prototype; after line 3.
or
create a new object and copy the properties:
var oi2 = new MyMagicalObject();
for (var p in oi) {
if (oi.hasOwnProperty(p)) {
oi2[p] = oi[p]
}
}
console.log(oi2.numFields());

how to null an object which is an array's element in javascript [duplicate]

This question already has answers here:
Deleting Objects in JavaScript
(14 answers)
Closed 8 years ago.
Suppose i have an Array of objects in javascript :
var obj0 = new Object();
var obj1 = new Object();
var obj2 = new Object();
var obj3= new Object();
var array = new Array(obj0,obj1,obj2,obj3);
if i write :
array[1] = null;
this will give me [obj0,null,obj2,obj3] what was nulled is the array case not the object itself; the obj1 won't really be nulled in the memory.
How to null an object by accessing it via the array ?
You just need to remove all references to the object, including the obj1 reference. Then the garbage collector will take care of the rest.
However, if your obj1 variable is a local variable (as it appears to be in your code snippet), you can just leave the reference as is. When the enclosing method returns, the local variable will be cleaned up, and subsequently, the nulled object as well.
I found a good article on Smashing Magazine that looks relevant to your question.
It’s not possible to force garbage collection in JavaScript. You
wouldn’t want to do this, because the garbage collection process is
controlled by the runtime, and it generally knows best when things
should be cleaned up.
http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
i think "splice()" will help:
http://www.w3schools.com/jsref/jsref_splice.asp
var obj0 = new Object();
var obj1 = new Object();
var obj2 = new Object();
var obj3= new Object();
var array = new Array(obj0,obj1,obj2,obj3);
array.splice(1); // kill index 1
The result: [obj0,obj2,obj3].
What if you tried to write it this way?
var array = new Array();
array[0] = new Object();
array[1] = new Object();
array[2] = new Object();
array[3]= new Object();
array[1] = null;
As commented Kpower, writting :
var array = [{}, {}, {}, {}];
or
var array = new Array(new Object(),
new Object(),
new Object(),
new Object());
and when nulling any array cell like :
array[1] = null;
this will effectively remove the reference for the object so it will be garbage collected.

Difference between javascript object literal notation and adding to objects

Can someone explain what is happening in the code below? I'd expect toString to get called for either both foo and bar, or neither. How is literal object notation different from adding fields to an object after it is created?
function Obj(v) {
this.v = v;
};
Obj.prototype.toString= function() {
window.alert("to string called for " +
this.v);
return this.v.toString();
}
var foo = new Obj('foo');
var bar = new Obj('bar');
// toString is not called here.
var map = {foo : 'blah'};
// toString is called here.
map[bar] = "blah2";
Why do object literals not use toString() while adding to an existing object does use toString()?
http://jsfiddle.net/pByGJ/2/
The main reason that object literals don't evaluate the identifier to the left of the colon is so you're not force to quote all literal names (as you do in JSON).
Bracket notation forces you to quote property names, if you don't, it will be evaluated as a variable.
The reason toString() does get called in the second example is because bar has to be converted to a string to be used as a property name.
In your first example, you're just creating a literal object (that is the exactly the same as {"foo" : 'blah'}). So that is never using the variable foo
If you want to create an object using a variable name, you can't use literal object notation, you have to use [] which is what forces it to call toString()
Here's a function to create objects with variable names in one expression.
function obj(key, value /*, key, value, ... */) {
var obj = {};
for (var i = 0, ln = arguments.length ; i < ln; i+=2) {
obj[arguments[i]] = arguments[i+1];
}
return obj;
}
Clearer Example
The fact that your variable names and values are the same doesn't help understanding the problem. Let me suggest this code
var foo = new Obj('fooValue');
var bar = new Obj('barValue');
var map = {foo : 'blah'};
map[bar] = "blah2";
// You expect map to be {fooValue: 'blah', barValue: 'blah2'}
// But it's {foo: 'blah', barValue: 'blah2'}
To do what you need, use my obj function
// Almost as clear as literal notation ???
var map = obj(
foo, 'blah',
bar, 'blah2'
);
// map = {fooValue: 'blah', barValue: 'blah2'} Yay!!
keys in an object literal are taken as strings, not interpreted as variables. This:
var map = {foo : 'blah'};
is equivalent to this:
var map = {"foo" : 'blah'};
and this:
var map = {};
map["foo"] = "blah";
but is completely different than this:
var map = {};
map[foo] = "blah";

Javascript arrays and JQuery .param

I've noticed something weird. I've always thought new Array() was the same as {}, however it seems to be different as {} seems to just be an object type whereas new Array() is an Array in the Chrome debugger.
So I've been using $.param(data), where data is the data from a $.ajax() call. I notice that when i have a params1 = new Array() and a params2 = {} inside the data, they come out differently.
params1 becomes
params1[]=1&params1[]=2
and params2 becomes
params2[0]=1&params2[1]=2.
The problem is that I had been using .param(data, false) because I noticed that params1[] was being serialized incorrectly, however .param(data, false) fails for params2 and gives me params2=[object+Object].
I figure I can get around this by just using .param(data) and stripping out "[]" so that regardless of it being initialized using {} or new Array, it'll still work out correctly. But I'd like to know if there's a better solution (short of always using {} vs new Array).
Kyliod,
In javascript {} is shorthand for creating a new Object, and [] is shorthand for a "new Array()."
SO:
var myArray1 = [];
var myArray2 = new Array();
var myObject = {};
myObject.objVariable1 = 'some string or other variable data';
var myObject2 = { obj2Var1 : 'some string', obj2Var2 : 1234, obj2Var3 : true };
// do stuff
var thing1 = myArray1[1]; // get something out of myArray1
var thing2 = myArray2[2]; // get something out of myArray2
var thing3 = myObject.objVariable1; // get something out of myObject
if(myObject2.obj2Var3)
{
// do other stuff
}
Hopefully this helps you clear up your jQuery / javascript Ajax issues.

Categories