JS - 动态创建2维数组Array (例子源码)

本文介绍了一个使用JavaScript实现的简单机制,用于存储与特定名称相关联的多个值,并能够在选择更改时检索这些值来更新页面元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<head>
</head>

<script type="text/javascript">
// Storing the list display value
var listArray;

/**
* Store the input value to listArray
* with identified by name.
*/
function setListArray(sName, sValue){
alert(sValue);
// listArray is null
if (listArray == null){
// Initialize the listArray
listArray = new Array();
// Store the first group
listArray[0] = new Array(sName, sValue);
}
// listArray is not null
else{
// declare flag
var valueFound = false;
for (var i = 0; i < listArray.length; i ++){
// find in the old array
if (listArray[i][0] == sName){
// store the value
listArray[i][listArray[i].length] = sValue;
// set flag when matched
valueFound = true;
// Exit for looping when matched
break;
}
}
//alert(listArray[0].length);
// new a group when not matched
if (!valueFound){
//var index = listArray.length;
listArray[listArray] = new Array(sName, sValue);
}
}
//alert(listArray[0].length);
}

/**
* get the value from listArray with name and index
*/
function getListArray(name, index){
if (index == 0){
return "";
}
// return false when listArray is null;
if (listArray == null){
alert("No listArray found!");
return false;
}
// Loop the listArray to found the object.
for (var i = 0; i < listArray.length; i ++){
if (listArray[i][0] == name){
// display the value
return listArray[i][index];
}
}
alert("No record could be found in listArray");
}

/**
* Set the value to the special Element
*/
function selectChanged(name, index, targetObj){
// get the target element
var obj = document.getElementById(targetObj);
// return false when target element cannot be found.
if (obj == null){
alert("Element '" + targetObj + "' cannot be found!");
return false;
}
obj.value = getListArray(name, index);
}
</script>
<body>
<table>
<tr>
<td>
<select name="sel" onchange="selectChanged('sel', this.selectedIndex, 'show')">
<option value="00">(none)</option>
<option value="01">name 01</option>
<option value="02">name 02</option>
<option value="03">name 03</option>
<option value="04">name 04</option>
</select>
</td>
<td>
<input type="text" name="show" value=""/>
</td>
</tr>
<tr>
<td colspan="2"><input type="button" value="disply"/></td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
setListArray('sel', 'name 01');
setListArray('sel', 'name 02');
setListArray('sel', 'name 03');
setListArray('sel', 'name 04');
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值