为什么在我记录字符串+对象时console.log记录不同的结果

时间:2019-02-07 12:46:06

标签: angular typescript

我目前正在尝试解决代码中的问题。为此,我正在记录对象,并在前面添加文本以确保日志来自何处。像下面两个例子一样:

console.log('TodoList Dialog Open: ' + todo);
console.log('Todo List get Todos ' + data);

注销上面的两个示例时,将得到以下输出:

Todo List get Todos [object Object],[object Object],[object Object]

前面没有任何字符串,我得到以下输出:

(3) [{…}, {…}, {…}]
0: {id: 392, taskName: "GMDU", dueDate: "2019-02-07", extraNote: "You have done it all wrong", taskCompleted: true}
1: {id: 391, taskName: "PMB", dueDate: "2019-02-07", extraNote: "Study you lazy ass!", taskCompleted: true}
2: {id: 393, taskName: "INMA", dueDate: "2019-02-07", extraNote: "Do something else", taskCompleted: false}
length: 3
__proto__: Array(0)

有没有一种方法可以记录对象并在其前面添加一个字符串?

感谢您的帮助!

5 个答案:

答案 0 :(得分:5)

用逗号+代替,

const arr = [{
  id: 392,
  taskName: "GMDU",
  dueDate: "2019-02-07",
  extraNote: "You have done it all wrong",
  taskCompleted: true
}, {
  id: 391,
  taskName: "PMB",
  dueDate: "2019-02-07",
  extraNote: "Study you lazy ass!",
  taskCompleted: true
}, {
  id: 393,
  taskName: "INMA",
  dueDate: "2019-02-07",
  extraNote: "Do something else",
  taskCompleted: false
}];

console.log('The first object is', arr[0]);
console.log('The whole array is', arr);

答案 1 :(得分:3)

因为首先定义了字符串,然后使用+串联运算符附加了对象,所以将其转换对象转换为字符串,这就是为什么要获得这样的输出

要解决您的问题,您需要使用,而不是+

console.log('TodoList Dialog Open: ' , todo);
console.log('Todo List get Todos ' , data);

答案 2 :(得分:0)

console.log可以接受任意数量的参数,因此您可以记录所有需要记录的数据,并以逗号分隔。

尝试一下:

console.log('TodoList Dialog Open: ', todo);
console.log('Todo List get Todos ', data);

Here是基于您的对象结构的有效提琴。在控制台标签中检查输出。

答案 3 :(得分:0)

console.log('TodoList Dialog Open: ' + todo);
console.log('Todo List get Todos ' + data);

// Here you use + to concat a string which is actually php syntax you have to change '+' sing with ',' 

console.log('TodoList Dialog Open: ' + todo);
console.log('Todo List get Todos ' + data);

答案 4 :(得分:0)

基本上,您尝试将其组合为一个字符串,而不是用,

进行分隔

console.log('Todo列表获取Todos',数据);