admin管理员组

文章数量:1293303

r = {
  name:'Bart',
  location:'Springfield' 
}

for(var a in r) {
  if (r.hasOwnProperty(a)) {
      console.log(a);
      const {a} = r[a]; // Here's where it's  failing.
      //I'm trying to do the equivalent of const{name} = r[a];
  }
}

console.log(name) //Expecting output `Bart`

In my attempt to destructure an object, I've attempted what's above. However, this gives me 'Uncaught ReferenceError: Cannot access 'a' before initialization`

Do you see any way using which this could be solved?

r = {
  name:'Bart',
  location:'Springfield' 
}

for(var a in r) {
  if (r.hasOwnProperty(a)) {
      console.log(a);
      const {a} = r[a]; // Here's where it's  failing.
      //I'm trying to do the equivalent of const{name} = r[a];
  }
}

console.log(name) //Expecting output `Bart`

In my attempt to destructure an object, I've attempted what's above. However, this gives me 'Uncaught ReferenceError: Cannot access 'a' before initialization`

Do you see any way using which this could be solved?

Share asked Jun 23, 2020 at 5:16 NormanNorman 6,36525 gold badges91 silver badges148 bronze badges 3
  • 1 Use a different variable name in the loop. – Teemu Commented Jun 23, 2020 at 5:17
  • Don't use a const and var with the same name in the same block-level scope – Phil Commented Jun 23, 2020 at 5:18
  • Actually a is name. I'm trying to the same thing as {name} = r[a] just like it's done in destructuring. – Norman Commented Jun 23, 2020 at 5:27
Add a ment  | 

2 Answers 2

Reset to default 5

On this line

const {a} = r[a];

You are trying to define a new variable a, which depends on using a to access a property of r.

Also, const { a } means you are trying to access the property a of r[a]. This can only work if r[a] returns an object which also has it's own keys to destructure like so:

r = {
  name: { a: 'Bart' },
  location: { a: 'Springfield' } 
}

In your code r[a] will return the values, which are both strings. This means they don't have a property a that you can destructure. In which case, I assume you meant to just assign it to a variable, instead of destructuring

To avoid the error, try to avoid naming conflicts, perhaps by using more readable variable names and skip the destructuring like so:

for(var key in r) {
  if (r.hasOwnProperty(key)) {
      console.log(key);
      const a = r[key];
  }
}
r = {
  name:'Bart',
  location:'Springfield' 
}

r.name contains 'Bari' (string type) value not any Object value. So distructuring causes problem in your statement const {a} = r[a] as r[a] isn't an object. And remember const and let are always scope bound. A possible workaround would be as follows

var r = {
  name:'Bart',
  location:'Springfield' 
}

for(var a in r) {
  if (r.hasOwnProperty(a)) {
      globalThis[a] = r[a];
  }
}

console.log(name)

本文标签: javascript cannot access 39a39 before initializationStack Overflow