Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在js/node.js中声明空变量/对象时如何停止容器的显示_Javascript_Node.js_Declare - Fatal编程技术网

Javascript 在js/node.js中声明空变量/对象时如何停止容器的显示

Javascript 在js/node.js中声明空变量/对象时如何停止容器的显示,javascript,node.js,declare,Javascript,Node.js,Declare,输出: 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 r

输出:

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);
我想声明一个空数组,但不显示“[]”,这样它只会说:
“你觉得Node.js怎么样?”

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

What do you think of Node.js? []
另一个选项是,您可以只
join()
数组元素,它将为空数组提供一个空字符串,为非空数组提供一个逗号分隔的列表

//if it has any length display array as normal
//otherwise just pass empty string
console.log( x.length? x : "" );
最后一个选项是使用自定义检查功能console.log最终会为对象调用或类似的本机函数。因此,您可以添加一个字符串,该字符串允许您返回要为该对象显示的内容

因此,再次测试数组的长度,在空数组的情况下返回一个空字符串,或者返回
util.inspect
方法将返回的内容

console.log(x.join())

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

对不起,我完全不明白你的问题。请您将问题修改得更清楚一点好吗?如果您询问如何使其不显示
[]
,请不要包含
console.log(x)
,因为
x
在您到达行的点是
[]
。。。
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]);
});