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?
4 Answers 4
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.
Comments
That's because positionData is an object (the object you return from spotJoinPosition) and (削除) the variable the variable width is undefined (削除ここまで)width contains a value that is not present on the object.
You want positionData.width or positionData['width'].
1 Comment
positionData[width] is outputting undefined is because width is defined somewhere, but the value of width is not a valid key in his positionData object.Try:
alert(positionData.offset);
alert(positionData.width);
alert(positionData.height);
Comments
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