Javascript:从具有相同名称的多个变量获取最后结果

时间:2018-01-11 08:26:17

标签: javascript jquery

在尝试修复以前程序员的错误时,我发现了一个if函数,它给出了与我们的链接混淆的相同变量多个信息。

// This piece of script, when there is multiple 'x' selections:
if (x == 0){
  var searchBrand = ""
}
else if (x == 1) {
  var searchBrand = "one"
}
else if (x == 2) {
var searchBrand = "two"
 }
else if (x == 3) {
  var searchBrand = "three"
}
else if (x == 4) {
  var searchBrand = "four"
}
else if (x == 5) {
  var searchBrand = "five"
}

// and processed via:
var newurl = $(this).attr('href').replace('/search?q=', '/search?q=' + searchBrand + '%20'+ '%20'+ '%20');

// output in reverse order selected:
/search?q=four%20%20%20two%20%20%20five%20%20%20

我尝试了类似的方法:

else if (x == 3) {
  var sB = { searchBrand: three; }
}
var newurl = $(this).attr('href').replace('/search?q=', '/search?q=' + sB.searchBrand + '%20')

和其他人。

我想要实现的是只获取newurl变量中最后选择的x的searchBrand值。

2 个答案:

答案 0 :(得分:0)

Declare searchBrand variable out side of else if ladder.

var searchBrand = "";

// This piece of script, when there is multiple 'x' selections:
if (x == 0){
   searchBrand = "";
}
else if (x == 1) {
   searchBrand = "one";
}
else if (x == 2) {
   searchBrand = "two";
 }
else if (x == 3) {
   searchBrand = "three";
}
else if (x == 4) {
   searchBrand = "four";
}
else if (x == 5) {
   searchBrand = "five";
}

答案 1 :(得分:0)

Use an array like this below

let searchBrand = ['','one','two','three','four','five']
var newurl = $(this).attr('href').replace('/search?q=', '/search?q=' + searchBrand[x] + '%20'+ '%20'+ '%20');

let queryParameter = ''
while(numberOfIterations){
    queryParameter = queryParameter+searchBrand[x]+'%20%20%20'
} //numberOfIterations is the number of times the value x is input

Also, I believe the question is not well framed. So could you reframe it better?