[英]Angular strange behavior in http response
I'm calling my api that returning a json in the response. 我正在调用我的api,它在响应中返回json。 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). 然后在控制台日志中,我得到2个索引(0,1)。 Why does this happen?
为什么会这样? (I know the built in console.log has some problems but really can not understand this)
(我知道内置的console.log有一些问题,但确实无法理解)
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];
})
}
This happens because javascript copy references, not values. 发生这种情况是因为javascript复制了引用,而不是值。 Something like pointers on
C
language. 类似于
C
语言上的指针。
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: 要在Javascript上克隆数组,您可以执行以下操作:
slice()
slice()
var a = [];
var b = a.slice();
var a = [];
var b = [...a];
This option will work only on ES6 compatible browsers (95.25% of users according to caniuse.com ] 此选项仅在兼容ES6的浏览器上起作用( 根据caniuse.com,有 95.25%的用户使用此选项)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.