gpt4 book ai didi

相当于 VBS redim 保留的 Javascript

转载 作者:行者123 更新时间:2023-12-03 08:25:03 26 4
gpt4 key购买 nike

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

该应用程序本质上允许用户输入新的员工编号以添加到数据库中,然后为其分配用户权限。不要问我为什么代码这么乱,不是我最初写的,我只是想让它在 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 的数组具有不同的语义,特别是它们实际上比真正的数组更接近向量,而且 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] 下标中的额外空间(即,它只需要某些值的额外维度空间的第 0 维而不是所有值),这使得这更简单,因为您不需要迭代每个第 0 维下标。

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

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

简单得多。

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

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 );
}

关于相当于 VBS redim 保留的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33590897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com