簡體   English   中英

http響應中的角度異常行為

[英]Angular strange behavior in http response

我正在調用我的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];
    })
}

發生這種情況是因為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. 傳播算子 (僅ES6)

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

此選項僅在兼容ES6的瀏覽器上起作用( 根據caniuse.com,有 95.25%的用戶使用此選項)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM