[英]Is there a way to change a variable’s value given its name in a function?
[英]javascript change function parameter variable name and return its value
嗨,我有一個函數,我想返回帶有附加值的函數參數。 所以不用寫這個:
function(response) {
return response.links_1;
}
function(response) {
return response.links_2;
}
function(response) {
return response.links_3;
}
我想做一個for循環,迭代並添加數字,如下所示:
function(response) {
var counter = 3;
for(var i = 0; i < counter; i++) {
return response.links_ +i;
}
}
重要的部分是response.link_不能為字符串! 然后松開功能參數值。
我嘗試這樣做:
function(response) {
var i = 1,
resp = 'response.links_',
endResp = resp + i;
return endResp ;
}
}
和console.log(endResp); 返回正確的字符串,但僅此而已,它是一個字符串..我想要變量 response.links_1的值,而不是字符串值response.links_1。
我剛剛嘗試了以下方法,但沒有任何運氣:(解析:只是一種主干方法)
parse: function(response) {
var counter = 3;
for(var i = 0; i < counter; i++) {
return response[links_ + i];
}
}
歡迎任何幫助。
您應該嘗試response [“ links_” + 3]
要訪問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']);
因此,您可以使用第二種方法
var counter = 3;
for(var i = 0; i < counter; i++) {
return response['links_' + i];
}
另外,您可以通過
var counter = Object.keys(response).length;
而且,如果您不需要對counter
變量做任何其他事情,並且response
對象僅包含鏈接,則可以使用類似
for (link in response) {
return response[link];
}
對象解除引用運算符.
不適用於動態生成的屬性名稱,因此必須使用數組取消引用運算符[]
:
return response['links_' + i];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.