简体   繁体   中英

Javascript - object keys / values

i want to know if i can set the same value for multiple keys in the following:

  1. React functional component state:
const [state, setState] = useState(
key1: 'same-value',
key2: 'same-value',
key3: 'same-value'
);
  1. React class component state:
state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'
};
  1. Javascript object :
const state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'
};

I want to know if something like this is possible:

const state = {
 state1, state2, state3: 'same-value';
};

I want to know if something like this is possible

Not in an object literal, no. You can do it after creating the object:

const state = {};
state.key1 = state.key2 = state.key3 = 'same-value';

Or you could make key2 and key3 accessor properties for key1 , meaning they'd track its value (change key1 , and you see the change in key2 and key3 ), because although using them looks like a simple property access, in fact it's a function call.

const state = {
    key1: 'some-value',
    get key2() { return this.key1; },
    get key3() { return this.key1; }
};
console.log(state.key1); // 'some-value'
console.log(state.key2); // 'some-value'
console.log(state.key3); // 'some-value'

I'm not suggesting that, just noting it's possible.

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