0

I'm calling my api that returning a json in the response. I'm calling as below:

getAllLearn() {
    this.learnService.getAllLearn().subscribe(res =>{
        // in result of log is I have res.featured which has only one index (0)
        console.log(res);
        this.myvar = res.featured;
    })
}

Then I add this code to the end:

this.myvar[1] = res.featured[0];

Then in console log I get 2 indexes (0,1). Why does this happen? (I know the built in console.log has some problems but really can not understand this)

Finally my code is:

getAllLearn() {
    this.learnService.getAllLearn().subscribe(res =>{
        // ---- Now it contains two indexes in my res.featured ----- 
        console.log(res);
        this.featured2 = res.featured;
        this.featured2[1] = res.featured[0];
    })
}
4
  • Did you parse the JSON? And what is in your Network tab on server response? P.S. It would be useful to see your service's logic Commented Jun 9, 2019 at 19:22
  • 1
    Don’t console.log to debug code, use a debugger instead. Commented Jun 9, 2019 at 19:29
  • @Sergey It has nothing to do with service. Service is simply sending an http request to server and servery just simply sending a json which the featured index has only one index. When I add the last line of code, this happesn. I think this mostly relates to console.log Commented Jun 9, 2019 at 19:30
  • @emix More info please? Commented Jun 9, 2019 at 19:31

1 Answer 1

1

This happens because javascript copy references, not values. Something like pointers on C language.

Example:

var a = [];
var b = a;

console.log(a.length); // 0
b.push('something');
console.log(a.length, b.length); // 1, 1

The same occurs with your code.

To clone an array on Javascript, you can do:

1. slice()

var a = [];
var b = a.slice();

2. Spread operator (ES6 only)

var a = [];
var b = [...a];

This option will work only on ES6 compatible browsers (95.25% of users according to caniuse.com]

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.