如果我有3个阵列......
var arr1 = new Array("qqq","www","eee","rrr");
var arr2 = new Array("aaa","sss","ddd","fff");
var arr3 = new Array("zzz","xxx","ccc","vvv");
我有一些带有与这些值匹配的单选按钮,是否可以使用单选按钮中的值来处理数组,例如
checkedRadioButton.length
获取数组的长度,该数组的长度与无线电选择中的值相同?
希望这很清楚
抱歉混淆。这是一些更多的例子;
<label>Radio buttons</label>
<input type="radio" name="radioGroup" id="s01" value="s01" checked="checked">
<label for="s01">Choice 1</label>
<input type="radio" name="radioGroup" id="s02" value="s02">
<label for="s02">Choice 2</label>
<input type="radio" name="radioGroup" id="s03" value="s03">
<label for="s03">Choice 3</label>
如果用户选择选项3,并且我想显示第3个数组中的值,那么最好的方法是什么?
答案 0 :(得分:1)
您可以使用JavaScript对象文字并使用数组名称作为键:
var data = {
arr1 : ["qqq","www","eee","rrr"],
arr2 : ["aaa","sss","ddd","fff"],
arr3 : ["zzz","xxx","ccc","vvv"]
}
var buttonVal = "arr1"; // depends on your HTML code
alert(data[buttonVal].length);
答案 1 :(得分:1)
从这里可以看出:http://jsfiddle.net/82XY5/
Html:
<form action="">
<input id='arr1' type="radio" name="arr" value="arr1">arr1<br>
<input id='arr2' type="radio" name="arr" value="arr2">arr2<br>
<input id='arr3' type="radio" name="arr" value="arr3">arr3
</form>
使用Javascript:
var arrayContainer = {};
arrayContainer["arr1"] = new Array("qqq","www","eee","rrr");
arrayContainer["arr2"] = new Array("aaa","sss","ddd","fff");
arrayContainer["arr3"] = new Array("zzz","xxx","ccc","vvv");
var value = document.getElementById("arr1").value;
alert(arrayContainer[value].length);
它的作用是:
arrayContainer
)。如果它们是全局变量,则公共范围为window
。[]
运算符访问具有所需名称的属性(变量)。 注意:没有必要对数组和对象使用new
关键字。
您可以var arr1 = ["qqq","www","eee","rrr"];