6

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

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

That's because positionData is an object (the object you return from spotJoinPosition) and the variable width is undefined the variable width contains a value that is not present on the object.

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

See the MDN docs on member operators.

1 Comment

actually, the reason that 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.
0

Try:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.