How can I get the value from jQuery object?

I return some data (example below) and save it in a jQuery object (or is it an array, and am I confusing them?) When I register a variable that is an object in which it has the values ​​that I am looking for but how do I access data inside this object?

the code

$itemPosition = { 'top': $item.offset().top, 'left':$item.offset().left }, console.log($itemPosition); 

This will exit the system (expected in this case) top: 0 and left: 490 .

But how can I find out how to work with these values?

In addition, although this is probably obvious, I am still in the early stages of training. jQuery / Javascript sure guides are on their way, but so far the SO community has been invaluable for my training, so thanks for reading

J.

+4
source share
2 answers

This is a simple javascript object. Not a jQuery object, not an array.

Access to the properties of the object will work as follows:

  $itemPosition.top; $itemPosition.left; 

Placing a $ as the first character of a name is valid, but can be confusing, as this is the convention used when storing a jQuery object.

Another valid way to access the properties of your object is to use square brackets, for example:

  $itemPosition['top']; $itemPosition['left']; 

Using the square brackets method, you can also pass variables, for example:

 var myTopString = 'top'; $itemPosition[myTopString]; 

If you want to iterate over all the values ​​in an object, you can do the following:

 for(var n in $itemPosition) { alert( n + ': ' + $itemPosition[n] ); } 

This will be the alert() key and value of each property of the object. As you can see, it uses the square bracket method, passing the key for each property stored in variable n .

That is all I have to say about it. -F. Gump

+12
source

If I'm not mistaken, you can simply use the properties:

 $itemPosition = { 'top': $item.offset().top, 'left':$item.offset().left }, console.log($itemPosition.top); console.log($itemPosition.left); 

All you did was create a javascript variable called $itemPosition with an anonymous type. It has two properties called top and left .

+1
source

Source: https://habr.com/ru/post/1310309/


All Articles