0

Is it possible? I'm trying to do the following thing:

var foo = 'foo';
var bar = 'bar';

var x;
var y;

var array1 = [x, [foo, y]];
var array2 = [x, [foo, bar], [foo, y]];

console.log(array1[0]); //undefined
console.log(array1[1][1]); //undefined

console.log(array2[0]); //undefined
console.log(array2[2][1]); //undefined

array1[0] = 'working';
array2[0] = 'working';

y = 'hello';

console.log(array1[0]); //working
console.log(array1[1][1]); //undefined

console.log(array2[0]); //working
console.log(array2[2][1]); //undefined

Although it's obvious to define value when you know where the binding value exist ,x in this case, it's hard to bind a value to values with unknown location, y in this case.

Any thoughts? Thanks.

5
  • 2
    It's not really obvious what you're trying to do, but you should probably read up on how variables are passed in javascript, and then read up on how pass-by-value works ? Commented Jan 21, 2014 at 16:47
  • Well, I know how variables are passed in JS. I don't agree what I'm trying to do is obvious. That is why you said you should probably read up on how variables are passed in javascript Commented Jan 21, 2014 at 16:50
  • I didn't say it was obvious, I said it was not obvious as there is no explanation of either the code or the problem ? Commented Jan 21, 2014 at 16:53
  • I was trying to say I don't agree what I'm trying to do is NOT obvious. and in such a obvious question, I always observe such an unproductive commenters tends to gather because the topic IS easy. I've got an answer from who understood the issue, anyway. Commented Jan 21, 2014 at 17:00
  • And to whom vote to close this Question. As you see there's a valid answer and 3 upvotes instantly. Which indicates a fact this Q&A is understandable and useful information to some people for sure. I don't like unproductive Topic Closer around here since they basically destroy value of this site. Commented Jan 21, 2014 at 17:12

1 Answer 1

2

It sounds like what you want is some kind of wrapper:

var x = {};
var y = {};

var array = [x, [foo, y]];

console.log(array[0].value); // undefined
console.log(array[1][1].value); // undefined

x.value = "hello";
y.value = "goodbye";

console.log(array[0].value); // hello
console.log(array[1][1].value); // goodbye
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Russell Zahniser. This seems to be a way. Appreciated.

Your Answer

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