I'm trying to assign an object value to a variable that is defined later in my code (in other words, assigne the value to an address), such as:
var memory;
var object = {};
object.mem = memory;
memory = 'hop';
console.log(object.mem);
would return 'hop'
You cannot do it with a primitive directly but you could create an object that acts as a pointer which contains the value. You end up with an extra layer of indirection but that might meet your needs. e.g.
var memoryPointer = {
value : null
};
var object = {};
object.mem = memoryPointer;
memoryPointer.value = 'hop';
console.log(object.mem.value);
To make object.mem == hop, I have a few answers
1.
var memory;
var object = {};
object.mem = memory;
memory = 'hop';
object.mem = memory;
console.log(object.mem);
Because when you assigned object.mem = memory, memory was undefined.
So you could just assign memory before the object.
Related
I keepy getting TypeError: testsession.testset[0].athletes is undefined - i have tried lots of different ways, is it not possible to have an array of arrays of objects
var testsession = {};
var testsetname = {};
var testset = [];
testsession.testsetname = testsetname;
testsession.testsetname = "week9";
testsession.testset = testset;
testsession.testset.push("400M");
testsession.testset.push("800M");
var athletes = [];
var Time = "49.2";
var AthleteID = "a92";
var athlete = { "AthleteID": AthleteID, "Time": Time};
//console.log(pointer);
testsession.testset[0].athletes = athletes;
testsession.testset[0].athletes.push(athlete)
console.log(testsession.testset[0].athletes[0]);
The testset[0] is a string. Make it an object
var testsession = {};
var testsetname = {};
var testset = [];
testsession.testsetname = testsetname;
testsession.testsetname = "week9";
testsession.testset = testset;
//Earlier you pushed 400m directly which is a string hence causing the error later on
testsession.testset.push({distance: "400M"});
testsession.testset.push({distance: "800M"});
var athletes = [];
var Time = "49.2";
var AthleteID = "a92";
var athlete = { "AthleteID": AthleteID, "Time": Time};
//console.log(pointer);
testsession.testset[0].athletes = athletes;
testsession.testset[0].athletes.push(athlete)
console.log(testsession.testset[0].athletes[0]);
testsession.testset[0] is a primitive value, a string.
The following statement will therefore not have the effect you may think it has:
testsession.testset[0].athletes = athletes;
What happens here? The primitive at the left has no athletes property, but JavaScript will coerce it to a String object, then assign that property to that temporary String object, which then disappears into oblivion.
So it is like that assignment never happened: testsession.testset[0] will remain a primitive value, and primitive values have no properties.
When you read the athletes property, the same will happen again: JavaScript coerces it to a String object, only to find that object has no athletes property, and so you get undefined.
When you try to access testsession.testset[0] that entry is a string. You maybe at least would like to set testsession.testset[0] = {}; before accessing its members.
I think you are working code like this.
<script >
var testsession = {};
testsession.testset = [];
testsession.testset.push({testsetname:"week9"});
testsession.testset[0].list = [];
testsession.testset[0].list.push({distance:"400M"});
testsession.testset[0].list[0].athletes = [];
testsession.testset[0].list[0].athletes.push({ AthleteID: "a92", Time: "49.2"});
testsession.testset[0].list.push({distance:"900M"});
testsession.testset[0].list[1].athletes = [];
testsession.testset[0].list[1].athletes.push({ AthleteID: "a93", Time: "99.2"});
console.log(testsession);
</script>
and result will be like that:
"{"testset":[{"testsetname":"week9","list":[{"distance":"400M","athletes":[{"AthleteID":"a92","Time":"49.2"}]},{"distance":"900M","athletes":[{"AthleteID":"a93","Time":"99.2"}]}]}]}"
I need to assign a value to nested object variable . The nested object variable will be given as
a.b.c
and the object will be given as
result
I need to create a variable
result[a][b][c]
so that i can bind value to this variable. Initially the result object only initialized as
var result = {}
This way you can do it
var a = 1, b = 2, c = "example";
var result = {};
result[a] = {};
result[a][b] = {};
result[a][b][c] = yourValue;
I feel puzzled when I rethink of these two functions:
The first one goes like this:
var test = [1,2,3];
var ele = test[0];
ele= 2;
alert(test[0]);
The result is 1. I think this is obvious. But when I meet this:
var test = [{id:1},{},{}];
var ele = test[0];
ele.id = 2;
alert(test[0].id);
The result turns to be 2
So could anyone tell me that how the javascript work when it happens like this in the object array?
In JavaScript, objects are assigned by reference, rather than copied in memory. So if you assign an existing object to a different variable, both will point to the same object in memory. Modifications to either will therefore be reflected in both.
var a = {id: 1, name: "bob"};
var b = a;
console.log(b.name); // bob
b.name = "bill";
console.log(a.name); // bill
So in your example, executing ele.id = 2; operates on the memory location holding the object at test[0]. The change to the id property of that object is reflected in both variables referencing it (test[0], ele)
Note that if you had assigned the entire array test to ele, modifying one of the array members would have been reflected in both test, ele since Arrays are objects in Javascript:
var test = [1,2,3];
// Assign array test to ele
var ele = test;
// Modify one member
ele[0] = 2;
alert(test[0]); // 2
I'm faced with a situation in JavaScript when I need to update an object via its pointer similar to ะก++ array of pointers to objects
Example code for my issue:
var foo = new Array();
var bar = function(){
this.test = 1;
foo.push(this); // push an object (or a copy of object?) but not pointer
};
var barInst = new bar(); // create new instance
// foo[0].test equals 1
barInst.test = 2;
// now barInst.test equals 2 but
// foo[0].test still equals 1 but 2 is needed
So, how can I solve this? Should I use a callback or something like this or there is an easy way to help me to avoid copying the object instead pushing the raw pointer into an array?
JS is pass-by-value, so your original assignment was this.test = the value of 1, in my example, it's this.test = the object pointed to by ptr, so when I change ptr this.test changes as well.
var foo = [],
ptr = {val: 1},
bar = function(){
this.test = ptr;
foo.push(this); // push an object (or a copy of object?) but not pointer
},
barInst = new bar(); // create new instance
// foo[0].test.val equals 1
ptr.val = 2;
// foo[0].test.val equals 2
Although if you thought that foo.push(this); was similar, it isn't. Since this is an object, the array will indeed contain "raw pointers" to objects, just like you want. You can prove this simply:
foo[0].test = 3;
// barInst.test === 3
Which shows that it is indeed a pointer to the object that was pushed onto the array
"create object method pointer"
Object.defineProperty(Object.prototype,'pointer',{
value:function(arr, val){
return eval(
"this['"+arr.join("']['")+"']"+
((val!==undefined)?("="+JSON.stringify(val)):"")
);
}
});
ex of use
var o={a:1,b:{b1:2,b2:3},c:[1,2,3]}, arr=['b','b2']
o.pointer(arr) // value 3
o.pointer(['c',0], "new_value" )
I have searched this site and also googled but can't seem to find the answer.
I need to create object instances dynamically where the instance name is provided as variable, so rather than access the object properties using:
var n = 'abcd';
eval('var '+n+' = new myinst();');
abcd.property = value;
I need to access using a variable:
['abcd'].property = value;
But this does not appear to work - what am I missing ?
You shouldn't be using eval in that way. You can easily assign "dynamic" variables to some base object instead:
var baseObj = {};
var n = 'abcd';
baseObj[n] = new myinst();
baseObj[n].property = value;
This gives you full control over the variable, including the ability to delete it,
delete baseObj[n];
Or check if it exists,
n in baseObj;
You can do "variable variables" using the array notation, but you need to provide a context for it. In the global scope, that would be the window:
var foo = 'bar';
window[foo] = new myinst();
window[foo].property = 'baz';
alert(bar.property);
Substitute window for whatever other scope a variable variable should live in. Variable variables are really an anti-pattern that shouldn't be used though.
If it's a global you can use:
var n = 'abcd';
window[ n ] = new myInst();
window[ n ].property = value;