0

I have an js object

var myClass = Class.extend({
    _innerArr: [],
    add: function( id, url ){
        this._innerArr.push([id, url]);
    },
    delete: function( id ){
        $( this._innerArr ).each(function( index ){
            if ( $( this )[0]==id ){
                 this._innerArr.splice( index, 1); // Doesn't work!!! Uncaught TypeError: Cannot call method 'splice' of undefined 
            }
        });
    }
});

But, if code change on:

 var globalArr;

 var myClass = Class.extend({
    _innerArr: [],
    add: function( id, url ){
        this._innerArr.push([id, url]);
    },
    delete: function( id ){
        globalArr = this._innerArr;
        $( this._innerArr ).each(function( index ){
            if ( $( this )[0]==id ){
                 globalArr.splice( index, 1); // Work!!! 
            }
        });

    }
});

why this._innerArr not work? I don't want using adding variable in my project. Thinks, other way is...

3
  • Use a plain loop, not each Commented Mar 24, 2014 at 10:27
  • Moving the var into the delete function is enough, you don't need it completely global Commented Mar 24, 2014 at 10:28
  • You've got a large problem with your .innerArr Commented Mar 24, 2014 at 10:33

2 Answers 2

3

When using jQuery's .each() method, the function gets called with this as the current value of the array. You're using that when doing $( this )[0]. ($( this )[0] might be unnecessary btw.)

You don't need to create a global variable for this, but you might as well set a scoped variable in the delete function.

Alternately, you can just use a for loop instead of jQuery's each(). That's also a little faster.

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

Comments

0

The reason why this happens is because the scope of this changes inside of the .each() callback; this is a pretty well known phenomena and typically involves saving this in another variable outside of the function call.

Instead of splicing things yourself, you could make use of jQuery.grep():

this._innerArr = $.grep(this._innerArr, function(element) {
    return element[0] != id;
});

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.