I am returning some data (example below) and saving it to a jQuery object (or is this an array and I am confusing the two?) when I log the variable that is the object it has the values I am looking for but how do I access the data inside this object?
code
$itemPosition = {
'top': $item.offset().top,
'left':$item.offset().left
},
console.log($itemPosition);
This would log out (the in this case expected) top: 0
& left: 490
.
But how can I know work with those values?
Also, while this it is probably obvious I am still in the early stages of learning jQuery/Javascript rest assured that reference books are on their way, but so far the SO community has been invaluable to my learning, so thanks for reading!
J.
This is a plain javascript object. Not a jQuery object and not an array.
Accessing properties of an object would work like so:
$itemPosition.top;
$itemPosition.left;
Placing a $
as the first character of the name is valid, but may lead to confusion as it is a convention used when storing a jQuery object.
Another valid way to access the properties of your object is to use square brackets, as in:
$itemPosition['top'];
$itemPosition['left'];
Using the square bracket method, you can also pass in variables, like so:
var myTopString = 'top';
$itemPosition[myTopString];
If you want to iterate over all the values in your object, you can do the following:
for(var n in $itemPosition) {
alert( n + ': ' + $itemPosition[n] );
}
This will alert()
the key and value of each object property. As you can see, it uses the square bracket method, passing in the key for each property stored in the variable n
.
That's all I have to say about that. -F. Gump
If I'm not mistaken, you can just use properties:
$itemPosition = {
'top': $item.offset().top,
'left':$item.offset().left
},
console.log($itemPosition.top);
console.log($itemPosition.left);
All you've done is create a javascript variable called $itemPosition
with an anonymous type. It has two properties called top
and left
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With