Eloquent Javascript, listToArray. Why does my for loop return rest [object] when input array has more than 3 elements -
i'm working through eloquent javascript chapter 4. exercise asks
write function arraytolist builds data structure previous 1 when given [1, 2, 3] argument
using code below can necessary output - when number of elements in array 3 or less.
function createnode (value, rest) { return { value: value, rest: rest } }; function arraytolist(arr) { var index = arr.length; firstnode = createnode(index,null); listbuild = firstnode; (i =(index-1); >0; i--) { listbuild = createnode(i,listbuild) }
question arraytolist([1,2,3]) produces desired result of "{ value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }"
arraytolist([1,2,3,4]) produces output of "{ value: 1, rest: { value: 2, rest: { value: 3, rest: [object] } } }"
why function generate rest property of [object] in case?
thanks!
your function seems work fine, suspect output issue, not problem code.
if you're using node.js test code, you've run gotcha implementation of console.log
. in node.js, console.log
formats objects using util.inspect
, , default util.inspect
display nested objects depth of 2. can change calling util.inspect
directly , using depth
option. set higher number, or can set null
unlimited depth:
var util = require('util'); var result = arraytolist([1,2,3,4]); console.log(util.inspect(result, { depth: null }));
Comments
Post a Comment