Javascript 相当于 VBS redim 保留

Javascript equivalent of VBS redim preserve

我正在尝试将一些旧的 VBScript 重写为 Javascript 用于 ASP.NET 应用程序,但有一行我不确定如何翻译,我什至不完全肯定它在做什么。

该应用程序本质上允许用户输入新的员工编号以添加到数据库中,然后为其分配用户权限。别问我为什么代码这么乱,不是我最初写的,我只是想让它在Chrome

中运行

这是我到目前为止翻译的相关代码:

if(form1.txtEmpno.value != ""){
var oOption;
oOption = document.createElement("OPTION");
oOption.text=form1.txtEmpno.value;
oOption.value=form1.txtEmpno.value;
form1.lstActive.add (oOption);
oOption = document.createElement("OPTION");
oOption.text="";
oOption.value="";
form1.lstPerms.add (oOption);
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value;
arrUsers(1,ubound(arrUsers,2)) = "";
form1.txtEmpno.value = "";
oOption = null;
}

这是有问题的行:

redim preserve arrUsers(1,ubound(arrUsers,2)+1);

MSDN 将 ReDim [Preserve] varname(subscripts) 定义为:

The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.

If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.

JavaScript 中的数组与 VBScript 的数组具有不同的语义,特别是它们实际上更接近 vector 而不是真正的数组,而且 JavaScript 不提供真正的数组N 维数组:改为使用交错数组(数组中的数组)。这意味着您的 VBScript 不能 语法 转换为 JavaScript.

这是您在 VBScript 中的相关代码:

ReDim Preserve arrUsers(1,ubound(arrUsers,2)+1)
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value
arrUsers(1,ubound(arrUsers,2)) = ""

我们看到arrUsers是一个二维数组。这需要转换成交错数组,但是你还没有发布定义和初始化的代码arrUsers,也没有发布后面的使用方式,所以我只能做假设。

它看起来是在最后一个维度上添加 1 个元素,但是代码似乎只在 [1] 下标中使用了额外的 space (即它只想要额外的维度 space 对于第 0 维的某些值而不是所有值),这使得这更简单,因为您不需要遍历每个第 0 维下标。

JavaScript 数组有许多我们将使用的函数属性,特别是 push:它将一个元素附加到数组的末尾(必要时在内部增加缓冲区),以及pop 从数组中删除最后一个(索引最高的)元素(如果数组为空,则为 NOOP):

var arrUsers = [ [], [] ]; // empty, staggered 2-dimensional array
...
arrUsers[0].push( form1.txtEmpno.value );
arrUsers[1].pop();

简单多了。

但是,如果这个数组只是存储和表示数据的某些内部模型的一部分,那么您应该利用 JavaScript 对象原型而不是使用数组索引,因为这会使代码自描述,例如:

var User = function(empNo, name) {
    this.employeeNumber = empNo;
    this.name = name;
};

var users = [];
users.push( new User(1, "user 1") );
users.push( new User(23, "user 23") );

...

for(var i = 0; i < users.length; i++ ) {
    alert( users[i].name );
}