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:
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! 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); 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.
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
// 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
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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.