首页 > 解决方案 > 在 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? []

我想声明一个不显示'[]'的空数组,这样它只会说:“你觉得Node.js怎么样?”

标签: javascriptnode.jsdeclare

解决方案


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

//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,最终会为对象调用或类似的原生函数。因此,您可以添加一个自定义检查函数,该函数允许您返回一个字符串,该字符串包含您希望为该对象显示的内容。

因此,您只需测试数组的长度,在空数组的情况下返回一个空字符串,或者返回该util.inspect方法原始返回的内容

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});
}

当然,这种方法会影响所有被记录或检查的数组,所以只有在需要时才使用它。


推荐阅读