简体   繁体   中英

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. Here is the original 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:

    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. 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. Also you need to use the "return" keyword when returning values form a function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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