JQUERY + Returns an array from a function

I am trying to return an array from the function call code below:

///////////// Generic Functions function spotJoinPosition() { var pos = { offset: $('div#spotJoinSite').offset(), width: $('div#spotJoinSite').width(), height: $('div#spotJoinSite').height() } return(pos); } var positionData = spotJoinPosition(); alert(positionData); alert(positionData[width]); 

When I warn positionData, I get [object] [object] and then undefined.

Tip

+6
source share
4 answers

alert(positionData[width]);

This is a key warning in positionData and using the width variable as the key. You did not define a variable called width , so it essentially looks for positionData[undefined] . You want positionData.width or positionData['width'] , but there is no reason for quotes.

Quotations are only required if you have a key with non-alphanumeric characters. positionData['some-key'] works, but positionData.some-key is a syntax error because variables cannot have - in them.

Also, your code MUST be an error because the width is nowhere defined. I am worried that you have a globally defined variable width somewhere in your code.

+6
source

That positionData is an object (the object you are returning from spotJoinPosition ) and , the width variable is undefined , the width variable contains a value that is not on the object.

You want positionData.width or positionData['width'] .

See MDN docs for member statements.

+1
source

Try:

  alert(positionData.offset); alert(positionData.width); alert(positionData.height); 
0
source

If you really want the generic function to return an array , not an object , you can review the following:

 ///////////// Generic Functions function spotJoinPosition(selector) { var el = $(selector), result = [el.offset(), el.width(), el.height()]; return(result); } var positionArray = spotJoinPosition("#spotJoinSite"); alert(positionArray[0]); // outputs the position alert(positionArray[1]); // outputs the width 
0
source

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


All Articles