JQUERY + Return an Array from a Function
I'm struggling to return an array from a 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 alert positionData I get [object][object] and then undefined.
Advice?
alert(positionData[width]);
This is alerting a key in positionData, and using the variable width
as the key. You haven't defined a variable called width
, so it's essentially looking up positionData[undefined]
. What you want is positionData.width
, or positionData['width']
, but there is no reason for quotes here.
Quotes would only be required if you had 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 SHOULD be erroring, because width isn't defined anywhere. I'm worried that you have a globally defined width
variable somewhere in your code.
That's because positionData
is an object (the object you return from spotJoinPosition
) and the variable the variable width
is undefinedwidth
contains a value that is not present on the object.
You want positionData.width
or positionData['width']
.
See the MDN docs on member operators.
Try:
alert(positionData.offset);
alert(positionData.width);
alert(positionData.height);
If you actually want a generic function that returns an array
and not an object
, you might want to revise to 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
精彩评论