POV
POV

Reputation: 12025

Why variable is not changed after modification?

I have Pagination class:

export class Pagination {
public localPagination(type: IPaginationLocal): void {
        this.paginationType = type;
        this.fetchData();
    }

 public fetchData() {
    this.paginationType.data = this.paginationType.data.slice(this.from, this.to);    
 }

}

Using:

    this.plans = [1,2,3,4,5,6,7,8,9,10];
    this.pagination.localPagination({
       data: this.plans,
       type: modePagination.LOCAL
    });
   console.log(this.plans);// It must be sliced

As you can see I pass variable this.plans to class: this.pagination.localPagination():

Then class makes slice input data in method fetchData().

After pagination execution I do:

 console.log(this.plans);

It should return sliced array, but returnы the initial array this.plans.

Upvotes: 0

Views: 41

Answers (3)

Matthias247
Matthias247

Reputation: 10426

You print the initial thing, not the thing you stored:

console.log(this.pagination.paginationType.data);

Array.prototype.slice returns a new array, it does not not modify the original one.

Upvotes: 0

Jayant Varshney
Jayant Varshney

Reputation: 1825

You should return the updated value as you are not modifying the actual reference.

export class Pagination {
public localPagination(type: IPaginationLocal): any {
        this.paginationType = type;
        this.fetchData();
        return this.paginationType.data;
    }

 public fetchData() {
    this.paginationType.data = this.paginationType.data.slice(this.from, this.to);    
 }

}

and use is like following

this.plans = [1,2,3,4,5,6,7,8,9,10];
    this.plans = this.pagination.localPagination({
       data: this.plans,
       type: modePagination.LOCAL
    });
   console.log(this.plans);// It must be sliced

Upvotes: 1

jdickel
jdickel

Reputation: 1457

You never change

this.plans

you are changing the variable

this.paginationType.data

Upvotes: 2

Related Questions