简体   繁体   English

javascript更改函数参数变量名称并返回其值

[英]javascript change function parameter variable name and return its value

Hi i have a function and i want to return the function parameter with an added value to the parameter. 嗨,我有一个函数,我想返回带有附加值的函数参数。 So instead of writing this: 所以不用写这个:

function(response) {
    return response.links_1;
}

function(response) {
    return response.links_2;
}

function(response) {
    return response.links_3;
}

I want to make a for loop that iterates through and adds the number, something like this: 我想做一个for循环,迭代并添加数字,如下所示:

function(response) {
    var counter = 3;
    for(var i = 0; i < counter; i++) {
        return response.links_ +i;
    }
}

The important part is that response.link_ must not be a string! 重要的部分是response.link_不能为字符串! Then it looses the function parameter value. 然后松开功能参数值。

I tried with doing this: 我尝试这样做:

function(response) {
    var i = 1,  
    resp = 'response.links_',
    endResp = resp + i;
    return endResp ;
    }
}

And console.log(endResp); 和console.log(endResp); returns the correct string, but thats just it, its a string.. i want the value of the variable response.links_1 not the string value response.links_1. 返回正确的字符串,但仅此而已,它是一个字符串..我想要变量 response.links_1的值,而不是字符串值response.links_1。

I have just tried the following without any luck: (the parse: is just a backbone method) 我刚刚尝试了以下方法,但没有任何运气:(解析:只是一种主干方法)

parse: function(response) {
    var counter = 3;
 for(var i = 0; i < counter; i++) {
   return response[links_ + i];
}
}

Any help is welcome.. 欢迎任何帮助。

您应该尝试response [“ links_” + 3]

To access the keys of a JSON hash, there are two ways 要访问JSON哈希的键,有两种方法

// For the following object
var obj = {
  links_1: 'value1',
  links_2: 'value1',
  links_3: 'value1',
};

// key1 can be accessed like
console.log(obj.links_1);

// Or
console.log(obj['links_1']);

So, in your case, you can use the second method 因此,您可以使用第二种方法

var counter = 3;
for(var i = 0; i < counter; i++) {
  return response['links_' + i];
}

Also, you can get the total count by 另外,您可以通过

var counter = Object.keys(response).length;

And, if you don't need to do anything else with the counter variable, and the response object only contains the links, you can use something like 而且,如果您不需要对counter变量做任何其他事情,并且response对象仅包含链接,则可以使用类似

for (link in response) {
    return response[link];
}

The object dereference operator . 对象解除引用运算符. doesn't work with dynamically generated property names, so you have to use the array dereference operator [] instead: 不适用于动态生成的属性名称,因此必须使用数组取消引用运算符[]

return response['links_' + i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM