Danny Danny - 2 months ago 8x
AngularJS Question

x = {} creates spontaneous object

Part of a larger program using AngularJs, the code fragment:

var thePortList = $scope.ipPortList; // an array of objects
console.log("before", $scope.ipPortList, thePortList);
thePortList[i] = {};
console.log("after", $scope.ipPortList, thePortList);

Creates this output:

before [] []
after [2: Object] [2: Object]

I have no idea why. I could expect to see something like this in a multi-threaded program but not in Javascript.

x = {} should assign a new, empty object to that element in the array. Right? I am baffled about this behavior. Can anyone shed some light?

Tested in Chrome on both my local machine and plunkr.

Plunkr here:

Complete plunkr console output: Plunker Link

Event tracked Multipane Show Preview Toolbar undefined undefined
editor-0.11.1.js:2 URL visited /?p=preview
VM631:29 portList []
VM631:34 processing 0 [] undefined
VM631:39 skipping 0
VM631:34 processing 1 [] undefined
VM631:39 skipping 1
VM631:34 processing 2 [] undefined
VM631:45 before [] []
VM631:47 after [2: Object] [2: Object]


It's a correct behavior, I think you misunderstand the meaning of log info. You can try this code in console, and see the result:

var a=[];

output: [undefined × 2, Object__proto__: Object]

The console log info '[2: Object]' omitted 2 undefined, in JavaScript if you assign a value to an array item which out of his length, undefined will automatically completed until the item index.