0
var ma = "jim";     
var nu = "123";    
var splitit = ma.split("");    
var splitit2 = nu.split("");    
for (i=0; i<=splitit.length;i++) {
    var bach = {splitit[i]:splitit2[i]};
}
alert(bach);
3
  • possible duplicate of Dynamic variable in javascript push function Commented May 7, 2013 at 12:07
  • Initializing variables inside of the for loop is not a good strategy for performance. It is better to cache it outside the loop and make reference to it. Please note. Commented May 7, 2013 at 12:10
  • @gabeno I don't see why they could be a difference (variable declarations are hoisted) and tests don't support your thesis either : jsperf.com/var-in-for-or-not Commented May 7, 2013 at 12:14

3 Answers 3

1

You probably want

var bach = {}; // create the object
for (i=0; i<=splitit.length;i++) {
    bach[splitit[i]]=splitit2[i]; // set a property according to the arrays
}

instead of

for (i=0; i<=splitit.length;i++) {
    var bach = {splitit[i]:splitit2[i]};
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use

var ma = "jim";     
var nu = "123";    
var splitit = ma.split("");    
var splitit2 = nu.split("");    
var bach = {};
for (i=0; i<=splitit.length;i++) {
    bach[splitit[i]] =splitit2[i];
}

Demo: Fiddle

Comments

0

You cannot use variables for property names in object literals, they always get interpreted literally. And you probably want only one bach object, instead of creating a new one each loop turn.

var bach = {};
for (i=0; i<=splitit.length;i++) {
    bach[splitit[i]] = splitit2[i];
}
alert(JSON.stringify(bach));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.