Maison > Questions et réponses > le corps du texte
P粉2486022982023-08-21 11:40:18
Voici ma solution :
function resolve(path, obj) { return path.split('.').reduce(function(prev, curr) { return prev ? prev[curr] : null }, obj || self) }
Exemple d'utilisation :
resolve("document.body.style.width") // 或者 resolve("style.width", document.body) // 或者甚至使用数组索引 // (someObject已在问题中定义) resolve("part.0.size", someObject) // 当中间属性未定义时返回null: resolve('properties.that.do.not.exist', {hello:'world'})
P粉2421267862023-08-21 09:38:46
Il existe deux manières d'accéder aux propriétés d'un objet : notation par points : quelque chose.bar et notation entre crochets : quelque chose['bar'].
La valeur entre crochets peut être n’importe quelle expression. Par conséquent, si le nom de la propriété est stocké dans une variable, la notation entre crochets doit être utilisée :
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)