开发者

Getting an array out of a JQuery function

开发者 https://www.devze.com 2023-02-18 23:35 出处:网络
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 fu

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');
   开发者_StackOverflow社区         arr.push(bid);
        }
        else
        {
            $(this).css('background-color','#ececec');
        }
    });
    console.log($.unique(arr));
} 


  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();
    


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消