Rumah > Soal Jawab > teks badan
Saya cuba mengakses sifat objek menggunakan nama dinamik. adakah mungkin?
const something = { bar: "Foobar!" }; const foo = 'bar'; something.foo; // The idea is to access something.bar, getting "Foobar!"
P粉0989790482023-10-11 12:39:43
Ini penyelesaian saya:
function resolve(path, obj) { return path.split('.').reduce(function(prev, curr) { return prev ? prev[curr] : null }, obj || self) }
Contoh penggunaan:
resolve("document.body.style.width") // or resolve("style.width", document.body) // or even use array indexes // (someObject has been defined in the question) resolve("part.0.size", someObject) // returns null when intermediate properties are not defined: resolve('properties.that.do.not.exist', {hello:'world'})
P粉7558637502023-10-11 12:17:15
Terdapat dua cara untuk mengakses hartanah Objek:
something.bar
something['bar']
Nilai di dalam kurungan boleh berupa sebarang ungkapan. Oleh itu, jika nama sifat disimpan dalam pembolehubah, notasi kurungan mesti digunakan:
var something = { bar: 'foo' }; var foo = 'bar'; // both x = something[foo] and something[foo] = x work as expected console.log(something[foo]); console.log(something.bar)