Can you figure out why the name property of the merged object is properly set in the code below, even though the for-loop starts with i = 1?
function merge(root){
for ( var i = 1; i < arguments.length; i++ ){
for ( var key in arguments[i] ){
console.log(i); // returns 1 then 2 (not 0)
root[key] = arguments[i][key];
}
}
return root;
}
var merged = merge({name: "John"}, {city: "Boston"},{age: 13});
console.log( merged.name ); // "John" ?
console.log( merged.city ); // "Boston" - OK
console.log( merged.age ); // 13 - OK
If the loop starts with i = 2
, merged.city
would be undefined
as expected, but surprisingly, merged.name
still returns "John".
function merge(root){
for ( var i = 2; i < arguments.length; i++ ){
for ( var key in arguments[i] ){
console.log(i); // returns 2
root[key] = arguments[i][key];
}
}
return root;
}
var merged = merge({name: "John"}, {city: "Boston"},{age: 13});
console.log( merged.name ); // "John" - ?
console.log( merged.city ); // undefined - OK
console.log( merged.age ); // 13 - OK
Have you thought about how this situation could occur?