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);
-
possible duplicate of Dynamic variable in javascript push functionDenys Séguret– Denys Séguret2013-05-07 12:07:04 +00:00Commented 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.gmajivu– gmajivu2013-05-07 12:10:31 +00:00Commented 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-notDenys Séguret– Denys Séguret2013-05-07 12:14:56 +00:00Commented May 7, 2013 at 12:14
Add a comment
|
3 Answers
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
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));