0
var list = new Array(
    new Array("HAV", "TWI", "DOG-20::WHCH-2::WCBD-2"),
    new Array("TWI", "HAV", "DOG-20::WHCH-2::WCBD-2")
); 

<SELECT NAME="DESTINATION">
<OPTION VALUE="HAV">HAV</OPTION>
<OPTION VALUE="TWI">TWI</OPTION>
</SELECT>
<SELECT NAME="DESTINATION2">
<OPTION VALUE="TWI">TWI</OPTION>
<OPTION VALUE="HAV">HAV</OPTION>
</SELECT>

嘿,我将如何获取这个数组中某些东西的值?

如果 2 个选择设置为“HAV”和“TWI”,我希望获得一个值。

即如果输入是 HAV 和 TWI 得到 DOG 的值

4

3 回答 3

1
var list = new Array(
    new Array("HAV", "TWI", "DOG-20::WHCH-2::WCBD-2"),
    new Array("TWI", "HAV", "DOG-20::WHCH-2::WCBD-2")
); 

function checkDestinations(from, to, name) {
    for (var i = 0, len = list.length; i < len; i += 1) {
        if (list[i][0] === from && list[i][1] === to) {
            for (var dataByName = list[i][2].split("::"), j = 0; j < dataByName.length; j += 1) {
                var data = dataByName[j].split("-");
                if (data[0] === name) {
                    return data[1];
                }
            }
        }
    }
    return null;
}

console.log(checkDestinations("HAV", "TWI", "DOG"));
console.log(checkDestinations("HAV", "TWI", "WHCH"));
console.log(checkDestinations("HAV", "TWI", "WCBD"));

输出

20
2
2
于 2013-10-11T12:24:41.523 回答
0

首先给你的选择框一个ID

HTML

 <SELECT NAME="DESTINATION" id="DESTINATION">
    <OPTION VALUE="HAV">HAV</OPTION>
    <OPTION VALUE="TWI">TWI</OPTION>
    </SELECT>
    <SELECT NAME="DESTINATION2" id="DESTINATION2">
    <OPTION VALUE="TWI">TWI</OPTION>
    <OPTION VALUE="HAV">HAV</OPTION>
    </SELECT>

javascript

for(var i =0;i <list .length ;i++)
{
  var dogs = list[i];
  var dest = document.getElementById("DESTINATION").value;
  var dest2 = document.getElementById("DESTINATION2").value;
  if(dogs [0] == dest && dogs [1] == dest2 )
  {
      return dogs[2];
  }
}

这将返回 DOG-20::WHCH-2::WCBD-2;

于 2013-10-11T12:34:24.670 回答
0
var list = new Array(
  new Array("HAV", "TWI", "DOG-20::WHCH-2::WCBD-2"),
  new Array("TWI", "HAV", "DOG-30::WHCH-2::WCBD-2")
);

function getDog(p1, p2) {
  for (var i = 0, l = list.length; i < l; i++) {
    if (list[i][0] === p1 && list[i][1] === p2) {
      return /^DOG-([0-9]+)::WHCH-[0-9]+::WCBD-[0-9]+$/.exec(list[i][2])[1];
    }
  }
}

var dog = getDog('HAV', 'TWI'); // 20
var dog1 = getDog('TWI', 'HAV'); // 30

小提琴

您可以进一步使用第三个参数作为查询来获取其他值:

var list = new Array(
  new Array("HAV", "TWI", "DOG-20::WHCH-4::WCBD-7"),
  new Array("TWI", "HAV", "DOG-30::WHCH-5::WCBD-6") 
);

function getValue(p1, p2, query) {
  for (var i = 0, l = list.length; i < l; i++) {
    if (list[i][0] === p1 && list[i][1] === p2) {
      var regex = new RegExp(query.toUpperCase() + '-([0-9]+)');
      return regex.exec(list[i][2])[1];
    }
  }
}

var dog = getDog('HAV', 'TWI', 'DOG'); // 20
var whch = getDog('HAV', 'TWI', 'WHCH'); // 4

小提琴

于 2013-10-11T12:27:17.873 回答