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?
The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector. That way you can always call a method that is supposed to affect the elements found, even if there are no elements that matched.
The jQuery inArray() method is used to find a specific value in the given array. If the value found, the method returns the index value, i.e., the position of the item. Otherwise, if the value is not present or not found, the inArray() method returns -1. This method does not affect the original array.
The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.
Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With