为什么我有时需要使用JSON.stringify,有时候不需要

bil*_*_56 2 javascript json

有时在我的项目中,JSON.Stringify当我将值记录到控制台时,我正在使用a 来读取数据,有时我不需要这样做...我想知道为什么?

在这个例子中:

 this._productServices.getAll().do(data => console.log(data)).subscribe(products=> this.articles= products);
Run Code Online (Sandbox Code Playgroud)

当我看到控制台时,有这样的值:

(4) [{…}, {…}, {…}, {…}]
Run Code Online (Sandbox Code Playgroud)

Acctualy有可读的值数组.

但在这种情况下:

  filteredSubProducts: Group[];

 filterSubProductsByIdId(Id) {
    this.filteredSubProducts= this.articles.filter(item => item.parentId == Id);
    console.log("Products array" + this.filteredSubProducts);
  }
Run Code Online (Sandbox Code Playgroud)

我得到的结果如下:

Products array[object Object],[object Object]
Run Code Online (Sandbox Code Playgroud)

所以我需要JSON.stringify()在秒钟的情况下使用我的价值[object Object],[object Object]可读...我想知道为什么会这样?有时候我正在使用它,有时候我不是......

谢谢

epa*_*llo 6

您正在获取它,因为您正在向"Products array"Array 添加字符串filteredSubProducts.

所以代码实际上正在做

console.log("Products array" + this.filteredSubProducts.toString());
Run Code Online (Sandbox Code Playgroud)

toString()方法导致[object Object].

解决它的方法是不连接,但在console.log语句中使用逗号

console.log("Products array", this.filteredSubProducts)
Run Code Online (Sandbox Code Playgroud)

现在,它允许您在不使用JSON.stringify()的情况下显示它

现在,JSON.stringify()的优点在于它会在那时为您提供快照.有时您更改数组,对象并在控制台中显示为错误值对延迟评估.stringify会导致它被评估,并在那个时刻看到它.