http响应中的角度异常行为

时间:2019-06-09 19:21:04

标签: javascript angular

我正在调用我的api,该api在响应中返回json。我打电话如下:

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;
    })
}

然后将这段代码添加到末尾:

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

然后在控制台日志中,我得到2个索引(0,1)。为什么会这样? (我知道内置的console.log有一些问题,但确实无法理解)

最后我的代码是:

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];
    })
}

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为javascript复制了引用,而不是值。类似于C语言上的指针。

示例:

var a = [];
var b = a;

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

您的代码也是如此。

要在Javascript上克隆数组,您可以执行以下操作:

1。 slice()

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

2。 Spread operator(仅适用于ES6)

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

此选项仅在与ES6兼容的浏览器上有效(95.25%的用户according to caniuse.com]