![](/img/trans.png)
[英]why console.log doesn't show values of properties added by PROTOTYPES in javascript when whole object is printed?
[英]Why won't console.log show my whole javascript multidimensional array?
当我在Javascript中创建这样的数组时:
var tabInfos = [];
tabInfos[1] = [];
tabInfos[1]['label'] = 'one';
tabInfos[1]['id'] = '111';
tabInfos[2] = [];
tabInfos[2]['label'] = 'two';
tabInfos[2]['id'] = '222';
如何获取console.log(tabInfos)也显示第一个值(例如1、2):
您将第一项视为未定义的原因是因为它是。 JS数组从0开始,而您从1开始。
看一下获得似乎想要的东西的推荐方法-对象数组:
var tabInfos = [{ "label": "zero", "id": "000" }, { "label": "one", "id": "111" }, { "label": "two", "id": "222" }]; console.log(tabInfos); // or if you must console.log(JSON.stringify(tabInfos));
您应该使用对象,而不是内部项目使用数组。 它们不像数组。
var tabInfos = [];
tabInfos[1] = {};
tabInfos[1]['label'] = 'one';
tabInfos[1]['id'] = '111';
tabInfos[2] = {};
tabInfos[2]['label'] = 'two';
tabInfos[2]['id'] = '222';
您可以如下实现:
var i = 0;
JSON.stringify(tabInfos, null, 2).split(/\n/).forEach(function(line) {
window.console && console.log(
(/\s{2}\S/.test(line)) ? i++ + line : line
);
});
实际上,在您的屏幕截图中,控制台确实显示了tabInfos [1]和tabInfos [2]的第一个值,该值在负号[-]之后立即内联显示,并且因为其中没有值,因此在右边没有任何显示。
var tabInfos = [];
tabInfos[1] = {};
tabInfos[1].label = 'one';
tabInfos[1].id = '111';
tabInfos[2] = {};
tabInfos[2].label = 'two';
tabInfos[2].id = '222';
但是建议将tabInfos设置为对象而不是数组(然后可以使关联数组也意味着您可以具有命名属性)。
您担心第一个未定义的值吗? JavaScript数组的索引为0。 如果将第一个值设置为1,则第0个位置将自动变为未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.