Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Commit a39c639

Browse files
committed
util: Fix inspection for sparse array
Fixes #1651.
1 parent b86210f commit a39c639

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

lib/util.js

+28-4
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ function formatValue(ctx, value, recurseTimes) {
207207
base = ' ' + value.toUTCString();
208208
}
209209

210-
if (keys.length === 0) {
210+
if (keys.length === 0 && (!array || value.length == 0)) {
211211
return braces[0] + base + braces[1];
212212
}
213213

@@ -221,9 +221,14 @@ function formatValue(ctx, value, recurseTimes) {
221221

222222
ctx.seen.push(value);
223223

224-
var output = keys.map(function(key) {
225-
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
226-
});
224+
var output;
225+
if (array) {
226+
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
227+
} else {
228+
output = keys.map(function(key) {
229+
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
230+
});
231+
}
227232

228233
ctx.seen.pop();
229234

@@ -253,6 +258,25 @@ function formatPrimitive(ctx, value) {
253258
}
254259
}
255260

261+
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
262+
var output = [];
263+
for (var i = 0, l = value.length; i < l; ++i) {
264+
if (Object.prototype.hasOwnProperty.call(value, String(i))) {
265+
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
266+
String(i), true));
267+
} else {
268+
output.push('');
269+
}
270+
}
271+
keys.forEach(function(key) {
272+
if (!key.match(/^\d+$/)) {
273+
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
274+
key, true));
275+
}
276+
});
277+
return output;
278+
}
279+
256280
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
257281
var name, str;
258282
if (value.__lookupGetter__) {

test/simple/test-util-inspect.js

+8
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,11 @@ var orig = util.inspect(d);
3333
Date2.prototype.foo = 'bar';
3434
var after = util.inspect(d);
3535
assert.equal(orig, after);
36+
37+
// test for sparse array
38+
var a = [ 'foo', 'bar', 'baz' ];
39+
assert.equal(util.inspect(a), "[ 'foo', 'bar', 'baz' ]");
40+
delete a[1];
41+
assert.equal(util.inspect(a), "[ 'foo', , 'baz' ]");
42+
assert.equal(util.inspect(a, true), "[ 'foo', , 'baz', [length]: 3 ]");
43+
assert.equal(util.inspect(new Array(5)), '[ , , , , ]');

0 commit comments

Comments
 (0)