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 : "" );
最后一个选项是使用自定义检查功能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]);
});