1

I got a object name, set1 to set4 , I need to dynamically change their value in a loop with using eval() , or window, below example is using eval(), I had used window[] but still remain same result, that can't successfully changed the object's value with the 'make+set' function.

var set1 = {desc:"111",url:"http://photo1.com"};
var set2 = {desc:"222",url:"http://photo2.com"};
var set3 = {desc:"333",url:"http://photo3.com"};
var set4 = {desc:"444",url:"http://photo4.com"};

function make_set(set,desc,url) {
     set = {};
     set.desc = url;
     set.url = url;
    return set;
}

for (var i = 1; i < 5; i++) {
    tempSet = eval("set"+i);
    tempSet = make_set(tempSet,"new description","new url");
    console.log(tempSet)
};

console.log(set1);
console.log(set2);
console.log(set3);
console.log(set4);

I had overwrite the object with make_set function but still can't successfully changed the value with the function, am I doing it wrong on function? or I missed out anything?

Object {desc: "new url", url: "new url"}
Object {desc: "new url", url: "new url"}
Object {desc: "new url", url: "new url"}
Object {desc: "new url", url: "new url"}
Object {desc: "111", url: "http://photo1.com"}
Object {desc: "222", url: "http://photo2.com"}
Object {desc: "333", url: "http://photo3.com"}
Object {desc: "444", url: "http://photo4.com"}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Mavichow
  • 1,213
  • 17
  • 41

2 Answers2

1

You are creating a new object, and setting tempSet to that, not modifying existing sets.

for (var i = 1; i < 5; i++) {
    tempSet = eval('set' + i + ' = make_set(tempSet,"new description","new url")');
    console.log(tempSet);
};

But you really shouldn't use eval.

var sets = [];
sets[0] = {desc:"111",url:"http://photo1.com"};
sets[1] = {desc:"222",url:"http://photo2.com"};
sets[2] = {desc:"333",url:"http://photo3.com"};
sets[3] = {desc:"444",url:"http://photo4.com"};

function make_set(desc, url) {
    return {desc:desc, url:url};
}

for (var i = 0; i < 4; i++) {
    sets[i] = make_set("new description","new url");
    console.log(sets[i])
};

console.log(sets[0]);
console.log(sets[1]);
console.log(sets[2]);
console.log(sets[3]);
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
1

Remove the line set = {};

It's creating a new object, not changing the passed in object.

Live Demo

See the answers to "Why isn't this object being passed by reference when assigning something else to it?" for a more detailed explanation.

Community
  • 1
  • 1
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100