javascript 获取属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46206328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript getProperty
提问by Doug
I'm a complete beginner in regards to javascript and to coding in general. I'm planning to attend a coding boot camp soon, but part of the requirements for entry is I need to learn the basics first. I've been getting through the first few problems in regards to if/else quite easily, but then I ran into one that requires me to return a valuethat's assigned to a key. The function is called getPropertyand i'm just stuck. Unfortunately, each of the other questions build on know this one concept such as: addPropertyand removeProperty. Any help would be greatly appreciated as it would allow to me continue my studies! Below is what I have currently. I keeps returning "should return the value of the property located in the object at the passed in key" every time I try to run a test on the code.
在 JavaScript 和一般编码方面,我是一个完整的初学者。我打算很快参加一个编码训练营,但进入的部分要求是我需要先学习基础知识。我已经很容易地解决了与 if/else 相关的前几个问题,但后来我遇到了一个要求我返回分配给key的值的问题。该函数被称为getProperty,我只是被卡住了。不幸的是,其他每个问题都建立在知道这个概念的基础上,例如:addProperty和removeProperty. 任何帮助将不胜感激,因为它可以让我继续我的学业!以下是我目前所拥有的。每次我尝试对代码运行测试时,我都会不断返回“应该返回位于传入键的对象中的属性的值”。
I know that the question is probably really simple to solve, but there are just too many online resources to get a clear answer.
我知道这个问题可能真的很容易解决,但是有太多的在线资源无法得到明确的答案。
var obj = {key: 'value'};
function getProperty(obj, key) {
var o = obj.key;
return(o);
}
console.log(getProperty);
回答by Rob M.
For dynamic attribute names you need to use the bracket []notation instead of the dot notation:
对于动态属性名称,您需要使用括号[]表示法而不是点表示法:
var o = obj[key];
return o
Thanks to @Gaby for pointing out that you also need to call the function with valid arguments:
感谢@Gaby 指出您还需要使用有效参数调用函数:
console.log(getProperty(obj, 'key'));
回答by Abbas Reza
The "key" parameter for the method is irrelevant since you are not using it anywhere in the method. Also, the method needs the obj parameter when you call it.
该方法的“key”参数无关紧要,因为您没有在方法中的任何地方使用它。此外,该方法在调用时需要 obj 参数。
var obj = {key: 'value'};
function getProperty(obj) {
var o = obj.key;
return(o);
}
console.log(getProperty(obj));

