0

I have an interesting problem. Following is my javascript code . when i run line this.data.splice(k,1); gives an error:"Cannot call method 'splice' of undefined ". I understand the issue as within the each loop this.data is not recognized because "this" means each row of the array. the question is how do i call this.data in this case. I tried tried passing the object by ref but it;s not working. I appreciate your help. thanks.

var Pastopts = {
    index: 0,
    data: [ "one", "two", "three", "four", "five", "six", "seven" ],
    addOpt: function() {
          var  i = 0;
        $.each(this.data, function(k, v) {
            i++;
            if (i < 6) {
                this.data.splice(k, 1);
            }
        });
     console.log(this.data);
    }
}

Pastopts.addOpt();
0

1 Answer 1

1
var Pastopts = {
    index: 0,
    data: [ "one", "two", "three", "four", "five", "six", "seven" ],
    addOpt: function() {
          var  i = 0;
          var t_d = this.data;
        $.each(this.data, function(k, v) {
            i++;
            if (i < 6) {
                t_d.splice(k, 1);
            }
        });
     console.log(this.data);
    }
}

Pastopts.addOpt();
Sign up to request clarification or add additional context in comments.

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.