[英]How to return an object property through a function in javascript
I have a simple object and I want to call a particular property by passing a property name through a function: 我有一个简单的对象,我想通过函数传递属性名称来调用特定属性:
spit(name);
function spit(value) {
var test = new Object();
test.name = "Bill";
test.number = 24;
console.log(test.value);
}
The above code should return "Bill". 上面的代码应返回“账单”。 How is this possible?
这怎么可能?
Sounds like you're looking for something like this: 听起来您正在寻找这样的东西:
spit('name');
function spit(value) {
var test = new Object();
test.name = "Bill";
test.number = 24;
console.log(test[value]);
}
You are returning the value
property, which has not been defined for the object. 您将返回尚未为对象定义的
value
属性。 Also, you aren't quoting your parameter when calling spit()
, which might be a problem. 另外,调用
spit()
时不会引用参数,这可能是一个问题。
Try using this: 尝试使用此:
function spit(value) {
var test = new Object();
test.name = "Bill";
test.number = 24;
console.log(test[value]);
}
spit('name');
function spit(value) {
var test = {
name: 'Bill',
number: 24
}
test[value] = value;
return test.value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.