简体   繁体   English

将vbs转换为js:对于每个…in

[英]Converting vbs to js: for each … in

I'm converting some old VBScript to Javascript have two lines that I don't know how to convert properly. 我正在将一些旧的VBScript转换为Javascript,其中两行不知道如何正确转换。 Here is the original VBS: 这是原始的VBS:

function getCount()
        on error resume next
        dim allitems, strItemID, icnt
        icnt = 0
        set allitems = dsoITEMS.selectNodes("//item")
        for each node in allitems
            strItemID = node.selectsinglenode("item_id").firstchild.nodevalue
            if err then
                exit for
            end if
            if strItemID <> "" then
                icnt = icnt + 1
            end if
        next
        set nodes = nothing
        getCount = icnt     
end function

and here is the js I have so far: 这是我到目前为止的js:

    function getCount(){
   on error resume next;
   var allitems, strItemID, icnt;
   icnt = 0;
  allitems = dsoITEMS.selectNodes("//item");
   for each node in allitems;
    strItemID = node.selectsinglenode("item_id").firstchild.nodevalue;
    if(err){
     exit for;
    }
    if(strItemID != ""){
     icnt = icnt + 1;
    }
   next;
  nodes = null;
   getCount = icnt  ;
 }

the lines I can't figure out how to convert are "on error resume next" and "for each node in allitems" 我不知道如何转换的行是“错误时恢复下一个”和“针对项目中的每个节点”

Here's a conversion of your VBS code into JavaScript: Use try {} catch {} to trap errors. 这是将VBS代码转换为JavaScript的方法:使用try {} catch {}捕获错误。 When iterating through a collection of items, you can iterate using a for loop as shown below and access an item using the indexed property. 遍历项目集合时,可以使用如下所示的for循环进行迭代,并使用indexed属性访问一项。 Also you need to use the "return" keyword when returning values form a function. 当从函数返回值时,还需要使用“ return”关键字。

function getCount() {
    var allitems, strItemID, icnt;
    icnt = 0;
    try {
        allitems = dsoITEMS.selectNodes("//item");
        for(var i = 0; i<= allitems.length; i++){
            var node = allitems[i];
            strItemID = node.selectsinglenode("item_id").firstchild.nodevalue;
            if (strItemID !== ""){
                icnt = icnt + 1;
            }
        }
    }
    catch (ex){
        //Do something with the errors (if you want)
    }

    return icnt;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM