简体   繁体   中英

Javascript Object reference from Array

I have an object called o . I want to assign the elements of an array called newOb to the proprieties of o so that any change done with newObj will affect o . This works fine so far:

    let o = {}
    let c = {c:18}
    let newOb = [{a: 55}, {b: 55}]
    o.propA = newOb[0]
    o.propB = newOb[1]
    newOb[0].a++
    console.log(newOb, o)

Output:

 Array [Object { a: 56 }, Object { b: 55 }] Object { propA: Object { a: 56 }, propB: Object { b: 55 } }

Until this:

   let o = {}
    let c = {c:18}
    let newOb = [{a: 55}, {b: 55}]
    o.propA = newOb[0]
    o.propB = newOb[1]
    newOb[0] =  c
    console.log(newOb, o) 

Outputs

Array [Object { c: 18 }, Object { b: 55 }] Object { propA: Object { a: 55 }, propB: Object { b: 55 } }

When I try to change the element if newOb , the properties of o is not affected. Is there any solution for this issue?

  let o = {} let c = {c:18} let newOb = [{a: 55}, {b: 55}] o.propA = a => newOb[0] o.propB = a => newOb[1] newOb[0] = c console.log(newOb, o.propA(), o.propB()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM