javascript - 在 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怎么样?”
解决方案
一种快速的方法就是检查数组的长度并传递你想要显示的内容
//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});
}
当然,这种方法会影响所有被记录或检查的数组,所以只有在需要时才使用它。
推荐阅读
- omnet++ - 为什么设置停放的汽车会在 OMNeT 中产生错误
- magento - Magnolia 到 Magento 接口
- java - 几天后无法访问 Web 应用程序
- cuda - 从 CUDA 中并行的 n 个数组中搜索最小值/最大值(归约问题)
- php - PHP 表单在锚点单击时显示并跳转到 ie 但不是 chrome 中的正确位置。没有JS
- javascript - 用 JavaScript 为数学测验创建记分牌
- macos - Mac Catalina 在使用 loadstrings 时不会从 WebBrowser 加载链接
- android - 是否可以通过从集线器到 USB 端口的 USB 测试移动设备
- azure - 是否可以从 Azure Application Insights 中清除具体的自定义事件?
- sql-server - SQL Server“FOR XML”编码HTML实体?