The following code :
var obj = {uname:"OdO", age:"22"};
alert(obj.uname);
results in:
OdO
Now, using the same concept in a for..in statement :
for (x in obj) {
document.write(obj.x+"<br>");
}
I expected it to print the following:
OdO
22
but it prints :
undefined
undefined
And to achieve printing looping in the elements, it should be written as an array elements like this:
for (x in obj) {
document.write(obj[x]+"<br>");
}
Then, why the first syntax doesn't work, however it works out of the for..in statement ?
When you write obj.x, this literally looks for a property named "x" in obj — just like obj.size would look for a property named "size". x is not defined for your objects, so it comes out as nothing. The correct way of writing it — obj[x] — uses the variable x to look up a property in the object. The bracket syntax uses the value inside the brackets to look up the property, while the dot syntax turns the property name into a string. So these two are equivalent:
obj.x
obj["x"]
So when you write x after obj., it converts that x into a string — it's not a variable anymore.
The bracket syntax is used to receive a property whose name is the expression (expression can be a literal, a variable or something more complex):
var x = "a";
{a:0, b:1}[x] == 0;
The dot syntax is used to receive the property with exactly that name:
({a:0, x:1}).x == 1;
In your for-in-loop, the variable x holds the property name. You are trying to acess the property named "x", which is not defined.
Use the bracket form (obj[x]) when the property name is stored in a variable named "x" and the attribute form (obj.x) when the property name is literally "x".
For example:
var o = {foo:1};
o.foo; // => 1
var x = 'foo';
o[x]; // => 1, since x='foo' and has a property named "foo".
o.x; // => undefined, since "o" has no property named "x".
Try
for(var x in obj){
console.log(obj[x]);
}
This works for me:
var obj = {uname:"OdO", age:"22"};
for (x in obj) {
document.write(obj[x.toString()] + "<br>");
}
http://jsfiddle.net/zA8HB/
Related
vm.contributorAmountPerYear[index-1] gets me an object, and I want its key to be the year argument of the function.
function getAgriAmount(year,amount,index) {
if (typeof amount !== "number" ) {
amount = parseInt(amount ||0);
};
var argiYearlyLocalCost = vm.argiterraYearlyLocalCost;
console.log(vm.contributorAmountPerYear[index-1].year);
}
vm.contributorAmountPerYear[index-1][year]
For any javascript object, you should keep in mind that if you use . dot notation, you cannot access the properties for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case. This should work:
vm.contributorAmountPerYear[index-1][year];
Dot notation should be used when you already know the key:
var cuteJavaScriptObject = {
animal : 'cat'
}
var myVar = 'animal';
console.log(cuteJavaScriptObject.animal); // OK
console.log(cuteJavaScriptObject.myVar); // Wrong !!
console.log(cuteJavaScriptObject[myVar]); // Now OK
Does anyone know what is test[name] mean?
function test(value){
copy(value||{},this);
}
test[name] = function(){
return "test"
}
This will be easiest to explain with an example:
var name = "foo";
test[name] = function(){
return "test"
};
This would add a property named "foo" to the object test, and the value of that property is a function. It doesn't matter in this case that the object test is actually a function, you can assign properties to functions just like any other object in JavaScript.
You could call this function using any of the following methods:
test[name]()
test["foo"]()
test.foo()
Note that test[name]() will not work if the name variable is assigned to something different, for example name = 'bar'.
Javascript has two sets of notation for accessing objects, dot notation (obj.property) and bracket notation (object[property]). More on that at MDN.
test[name] = function (){} assigns an anonymous function to the name property on the the test object (which itself is a function). In this case (as noted by the comments) the variable name is being used to access the property.
This may seem a little strange at first, but it's helpful to remember that in javascript, functions are objects.
All functions in Javascript are also objects. This adds a property to the test function object with a value which is an anonymous function.
For example:
function test(){
return "foo";
}
// test is a function, so it is also an object and
// it can have properties assigned to it
test.x = function(){
return "bar";
};
test(); // "foo"
test.x(); // "bar"
Of course just like with any object you can also use bracket notation:
var name = 'hello';
test[name] = function(){
return "HELLO!";
};
test.hello(); // "HELLO!"
In JavaScript, functions are objects. They have properties. test[name] sets a property (named whatever the name variable holds) to a function.
when you have a javascript object with defined properties you can access the property either with the dot notation obj.property or with the square brackets notation obj[property]
the property could also be a function so if you have an object:
var test = {
foo : function(arg){ console.log(arg) },
bar : 'hello'
};
you can call test.foo('bar') also by doing test['foo']('bar')
This is especially useful in iterations or when you dont know a priori what the name of the property is going to be. For example:
var fun = 'foo';
test[fun]('hello world');
Naturally it's up to you to do proper checks such as
if ('function'==typeof test['foo']){ test['foo']('bar'); }
Also note that you can do checks on the fly like so:
test[ fun || 'foo']('hello');
Taken from the Mozilla page
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of object members
There are two ways to access object members: dot notation and bracket notation (a.k.a. subscript operator).
So
test[name] = function (
means: there are (if everything is ok) two objects: test and name (and we know that at least test is present, because you defined it one line before: function test(value))
take the test object (if there isn't a test object an error will happen). Then access the key/value pair with the key calculated from the name object and there put a function.
Now, how the key is calculated from the name object? The same page from before tells us:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
Note that the description is a little wrong... test[null] == test["null"] and test[undefined] == test["undefined"], so perhaps the truth is that under the covers something like String(key).valueOf() is done (the String function will convert null to "null" and undefined to "undefined")
Some examples (where => means "is equivalent to, with this values")
var name = 'foo';
test[name] => test['foo']
var name = 123;
test[name] => test['123']
var name = 123.3;
test[name] => test['123.3']
var name = new Date();
test[name] => test['Wed Aug 14 2013 17:35:35 GMT+0200 (...)']
var name = null;
test[name] => test['null']
var name = undefined;
test[name] => test['undefined']
var name = [];
test[name] => test['']
var name = [1,2,3];
test[name] => test['1,2,3']
var name = {};
test[name] => test['object Object']
and so on...
The brackets are how you reference a property via a key into the hash that javascript objects are.
Having an object like this:
var a = {
b: "string",
c: function(){
return "i return a string";
}
}
Doing
for (var key in a) {
console.log(typeof key);
};
Returns "string", "string" since b is a string and c returns a string.
Is there afunction that returns c -> function?
Returns "string", "string" since b is a string and c returns a string.
No. The reason it returns string, is that the attribute name b and the attribute name c are both strings; you're iterating over the keys of the object, not their values right now.
You could introduce attribute d, which was a function which returned a number or boolean, and you'd still get string.
Instead, enumerate over the values themselves;
for (var x in a) {
console.log(typeof a[x] );
};
If you want to see the type of the property instead of its key, should use the value together with the typeof operator.
for (var key in a) {
console.log(typeof a[key] );
};
Basically you will always get strings by iterating trough the keys of your object since they are represented as such.
But if you for example do console.log(typeof a[key]); Then you will get the expected output.
Change to:
for (var key in a) {
console.log(typeof a[key]);
};
Live DEMO
console.log(typeof key); // gives you the key - "c"
console.log(typeof a[key]); // gives you the value of the "c" key - function.
Let me explain this little bit, so it's easy to understand to anyone. (its my first post here anyway.)
Try the following code, it says its a function.
console.log(typeof(a.c))
But what you have written is reading the property names. Try the following code to understand what's wrong with your code.
for (var key in a) {
console.log(key);
};
So basically what you are getting is correct. Because all property names are string.
Remember JSON objects have several restrictions, such as case sensitive, full path needed to traverse to properties etc..
Change your code as follows to get the typeof your properties,
Solution 1:
console.log(typeof(a[key]));
Solution 2:
console.log(typeof(eval('a.'+ key)));
Like how you can have:
var obj = {};
obj.a = obj.b = 5;
obj.a === obj.b === 5; //just imagine that it won't evaluate to true === 5
Is there the same thing for object literals? Something along the line of:
var obj = {
a : b : 5
};
obj.a === obj.b === 5; //just imagine that it won't evaluate to true === 5
Is there the same thing for object literals?
No, there isn't. Although you can use any other expression on the right-hand side of the :, including an assignment expression, you can't use another property initialization expression. And you can't use an assignment expression instead (assigning to one of that object's properties) because the object hasn't been assigned to the target variable yet, so you have no way of referencing it.
How to get the value of key a and 'a' in javascript?
var obj = {a:1,'a':2}
The first key a will be overwritten by the second 'a'.
obj.a will return 2.
If your key name is a valid Javascript identifier or a number, Javascript will allow you to omit the quotes in key names. In practice, however, it's probably better to train yourself to always use quotes, to avoid confusion like this, and also because JSON requires them.
You can't - they are same key, and that initialiser will create an object with a single element 'a' with value '2'. Try this:
var obj = {a:1,'a':2};
for ( var i in obj )
{
alert(i + '=' + obj[i] );
}
And you'll just get "a=2' in response.
obviously, 'a' is the one-character string with a lowercase a as content; but what do you expect to be the other key? if you want it to be the value of a variable called a, then the curly braces syntax won't help you. Unlike Python, this syntax assumes the keys are strings, and quotes are optional.
You'd have to do something like this:
var a = 'givenkey'
var obj = {}
obj[a] = 1
obj['a'] = 2
this would create an object equivalent to:
var obj = {'givenkey':1, 'a':2}
If you not sure about key - use iteration
for(var k in obj)
alert(k + "=" + obj[k])
When you know key exact value use obj[k]
There isn't any difference.
alert([
obj.a,
obj['a']
].join("\n")); // returns 2 in both cases