2

I'm fairly new to JQuery. I've written the following function, I can view the created array in the console so I know that the function works okay. My question is how do use the array outside of the function? I've tried inserting return arr; at the end of the function, but I just can't seem to access the array values!

function css_ts() {
    arr = [];
    $('.timeslot').each(function(){
        var bid = $(this).children("input[type='hidden']").val();
        if (bid > 0) {
            $(this).css('background-color','blue');
            arr.push(bid);
        }
        else
        {
            $(this).css('background-color','#ececec');
        }
    });
    console.log($.unique(arr));
} 
2
  • How are you trying to use the returned value? Can you post that piece of code here? Commented Mar 19, 2011 at 23:30
  • The code is part of a booking system, the returned values are booking ids. The day is broken down into 15 min segments, the code above finds all the segments that have a booking in them. At the moment each 15 minute segment is a div element with a border, though one or more divs could have the same value, if say a booking lasts an hour. If that is the case I want the four div elements to look joined (ie change the CSS so the borders are removed between the divs). Therefore I would iterate over the returned array to find the bookings that where more than 15 mins and adapt the CSS accordingly Commented Mar 19, 2011 at 23:37

3 Answers 3

1
  1. arr inside css_ts is implicitly global, because you've omitted the var keyword. You should always use var when declaring/initializing a variable:

    var arr = [];
    
  2. Add the following line to the end of your function:

    return arr;
    

    Then use it like this:

    var arr = css_ts();
    
Sign up to request clarification or add additional context in comments.

Comments

1

Add a var before arr = [];, this makes it local for your function, and you will be able to return it at the end.

1 Comment

To be clear, you can return it even when it's global, but it will just return a reference to the global variable, as the following should demonstrate: var val = (function() { return test = "3" })(); val === window.test // true
0

Did you declared the arr[] inside the function or outside the function? If you did create it inside the function then no other function can see this variable because of the scope of the variable. Move the declaration outside of the function and give it a try. I hope this helps.

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.