我试图使用动态名称访问对象的属性。这可能吗?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
我试图使用动态名称访问对象的属性。这可能吗?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
当前回答
其他人已经提到了“点”和“方”语法,所以我想以类似的方式介绍访问函数和发送参数。
Code jsfiddle
var obj = {method:function(p1,p2,p3){console.log("method:",arguments)}}
var str = "method('p1', 'p2', 'p3');"
var match = str.match(/^\s*(\S+)\((.*)\);\s*$/);
var func = match[1]
var parameters = match[2].split(',');
for(var i = 0; i < parameters.length; ++i) {
// clean up param begninning
parameters[i] = parameters[i].replace(/^\s*['"]?/,'');
// clean up param end
parameters[i] = parameters[i].replace(/['"]?\s*$/,'');
}
obj[func](parameters); // sends parameters as array
obj[func].apply(this, parameters); // sends parameters as individual values
其他回答
通过引用查找对象,字符串, 注意,确保你传递的对象是克隆的,我使用cloneDeep从lodash
如果对象看起来像
const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]
路径看起来像这样
const objectPath = ['data',1,'person',name','last']
然后调用下面的方法,它将按给定的路径返回子对象
const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"
const findObjectByPath = (objectIn: any, path: any[]) => {
let obj = objectIn
for (let i = 0; i <= path.length - 1; i++) {
const item = path[i]
// keep going up to the next parent
obj = obj[item] // this is by reference
}
return obj
}
我遇到过这样的情况,我想把对象属性的“地址”作为数据传递给另一个函数,并填充对象(使用AJAX),从地址数组进行查找,并在另一个函数中显示。我不能使用点表示法而不做字符串杂技,所以我认为一个数组可能是很好的传递代替。我最终做了一些不同的事情,但似乎与这篇文章有关。
这是一个类似于我想要数据的语言文件对象的示例:
const locs = {
"audioPlayer": {
"controls": {
"start": "start",
"stop": "stop"
},
"heading": "Use controls to start and stop audio."
}
}
我希望能够传递一个数组,如:["audioPlayer", "controls", "stop"]来访问语言文本,在这种情况下是"stop"。
我创建了这个小函数,它查找“最不特定的”(第一个)地址参数,并将返回的对象重新分配给自己。然后它准备查找下一个最特定的地址参数(如果存在的话)。
function getText(selectionArray, obj) {
selectionArray.forEach(key => {
obj = obj[key];
});
return obj;
}
用法:
/* returns 'stop' */
console.log(getText(["audioPlayer", "controls", "stop"], locs));
/* returns 'use controls to start and stop audio.' */
console.log(getText(["audioPlayer", "heading"], locs));
我问了一个类似于这个主题的问题,经过大量的研究,看到了很多应该在这里丢失的信息,我觉得我有一些有价值的东西可以添加到这篇旧文章中。
首先,我想说明有几种方法来获取属性的值并将其存储在动态变量中。第一个最受欢迎,也是最简单的方法是:
let properyValue = element.style['enter-a-property'];
然而,我很少走这条路,因为它不工作的属性值通过样式表分配。为了给您一个示例,我将使用一些伪代码进行演示。
let elem = document.getElementById('someDiv');
let cssProp = elem.style['width'];
Using the code example above; if the width property of the div element that was stored in the 'elem' variable was styled in a CSS style-sheet, and not styled inside of its HTML tag, you are without a doubt going to get a return value of undefined stored inside of the cssProp variable. The undefined value occurs because in-order to get the correct value, the code written inside a CSS Style-Sheet needs to be computed in-order to get the value, therefore; you must use a method that will compute the value of the property who's value lies within the style-sheet.
因此,getComputedStyle()方法!
function getCssProp(){
let ele = document.getElementById("test");
let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}
这提供了一个很好的例子,并让您可以使用它,然而,这个链接Mozilla CSS getComputedValue文档详细讨论了getComputedValue函数,任何有抱负的开发人员如果对这个主题不完全清楚,都应该阅读。
顺便说一句,getComputedValue方法只获取,不设置。这显然是一个主要的缺点,但是有一个方法可以从CSS样式表中获取,以及设置值,尽管它不是标准的Javascript。 JQuery方法…
$(selector).css(property,value)
...是get,是set。这就是我所使用的,唯一的缺点是你必须了解JQuery,但这是每个Javascript开发人员都应该学习JQuery的许多很好的理由之一,它只是让生活变得简单,并提供了一些方法,就像这个,这在标准Javascript中是不可用的。 希望这能帮助到一些人!!
下面是一个ES6示例,说明如何使用通过连接两个字符串动态生成的属性名访问对象的属性。
var suffix = " name";
var person = {
["first" + suffix]: "Nicholas",
["last" + suffix]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person["last name"]); // "Zakas"
这称为计算属性名
您可以使用括号符号动态访问对象的属性。这看起来像obj[yourKey],然而JavaScript对象并不是为动态更新或读取而设计的。它们打算在初始化时定义。
如果你想动态分配和访问键值对,你应该使用映射。
const yourKey = 'yourKey'; //初始化它的值 const map1 = new Map([ (“yourKey”、“yourValue”) ]); //初始化为空,然后动态赋值 const map2 = new Map(); map2。集(yourKey yourValue); console.log (map1.get (yourKey)); console.log (map2.get (yourKey));