如何在 js/node.js 中声明空 variable/object 时停止显示容器

How to stop display of container when declaring an empty variable/object in js/node.js

const readline = require('readline');

x = [];

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  rl.close();
  console.log(answer);
  x.push(answer);
});

console.log(x);

输出:

What do you think of Node.js? []

我想声明一个不显示“[]”的空数组,这样它只会说: "What do you think of Node.js?"

一个快速的方法就是检查数组的长度并传递你想要显示的内容

//if it has any length display array as normal
//otherwise just pass empty string
console.log( x.length? x : "" );

另一种选择是您可以只 join() 数组元素,它将为空数组提供一个空字符串,为非空数组提供一个逗号分隔的列表

console.log(x.join())

最后一个选择是使用自定义检查功能。 console.log 在 nodejs 环境中最终调用 util.inspect, or similar native function, for objects. Because of this you can add a custom inspect function 允许您 return 您想要为该对象显示的字符串。

所以你再次测试数组的长度 return 一个空字符串在空数组的情况下或 return util.inspect 方法将具有原始 return埃德

Array.prototype[util.inspect.custom] = function(){
  if(!this.length){
    return "";
  }
  //passe customInspect:false so the custom inspect method wont be called again
  return util.inspect(this,{customInspect:false});
}

当然,此方法会影响所有正在记录或检查的数组,因此请仅在需要时使用它。

const readline = require('readline');

x = [];

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  rl.close();
  x.push(answer);
  console.log(x[0]);
});