为什么输出总是 [对象对象]

Why is the output always [object Object]?

本文关键字:对象 输出 为什么      更新时间:2023-09-26
var dev = [device.id](or null);
function console(stdout){$('#console').text(stdout)}
function adbShell(command){
if(dev==null){throw Error('adb >No KFSOWI detected')}
client.shell(dev,command)
 .then(function(output){console(output)})
};

我正在尝试创建一个函数来运行 adb shell 命令,并将输出返回到控制台,但我得到的唯一返回是 [对象对象]

这是因为"" + {} - 任何不定义toString对象的字符串化 - 会导致"[object Object]"。在这种情况下,转换为字符串可能发生在 .text 函数中。

正如 meanIOstack 所建议的那样,使用 JSON.stringify 创建一个"更有用"的字符串可能是有意义的。例如;

function console (obj) {
   var str = typeof obj === "string" ? obj : JSON.stringify(obj)
   $('#console').text(str)
}

另一方面,"真正的问题"可能是output没有计算到期望值;至少上述函数可以更好地了解返回的内容