简体   繁体   中英

JavaScript arrays declaration ways difference

This could be a pretty basic question, in JavaScript, what's difference between:

var userDetails = {};  
var usersList = [];  

I was reading an article which had following code:

 function GetSampleUsersList() {  
    var userDetails = {};  
    var usersList = [];  
    for (var i = 1; i <= 3; i++) {  
        userDetails["UserId"] = i;  
        userDetails["UserName"] = "User- " + i;  
        userDetails["Company"] = "Company- " + i;  
        usersList.push(userDetails);  
    }  
    return JSON.stringify(usersList);  
}  

Thanks

This is a pretty basic question.

var o = {}

initializes an empty object. Then you assign its properties.

 var a = []

initializes an empty array. You then add the newly created object to the array

a.push( o );

You are using for every iteration the same userDetails , because you overwrite just the properties and while you have pushed the same object, you have always the same content for every element in the array.

  function GetSampleUsersList() { var userDetails = {}; var usersList = []; for (var i = 1; i <= 3; i++) { userDetails["UserId"] = i; userDetails["UserName"] = "User- " + i; userDetails["Company"] = "Company- " + i; usersList.push(userDetails); } return JSON.stringify(usersList); } console.log(GetSampleUsersList()); 

Better use a new empty object for every loop.

  function GetSampleUsersList() { var userDetails; var usersList = []; for (var i = 1; i <= 3; i++) { userDetails = {}; // this is necessary userDetails["UserId"] = i; userDetails["UserName"] = "User- " + i; userDetails["Company"] = "Company- " + i; usersList.push(userDetails); } return JSON.stringify(usersList); } console.log(GetSampleUsersList()); 

 var userDetails = {}; -- object notation in javascript
 var usersList = [];  is an array notation in javascript.

for more infomation refer here http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

function GetSampleUsersList() {      
var userDetails = {};  //created an empty object userDetails 
var usersList = [];  //created an empty array userDetails
for (var i = 1; i <= 3; i++) {  //looping to add property and value in object and for each iteration object is getting pushed into array at an index i.
    userDetails["UserId"] = i;  
    userDetails["UserName"] = "User- " + i;  
    userDetails["Company"] = "Company- " + i;  
    usersList.push(userDetails);  // pushing object {"UserId":i, "UserName":"User-i", "Company":"Company-i"} into array
}  
    return JSON.stringify(usersList);  // Parsing the object into javascript string
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM