JScript Enumerator and list of properties

前端 未结 3 1069
南方客
南方客 2021-02-06 11:45

Consider the following WSH snippet:

var query = GetObject(\"winmgmts:\").ExecQuery(\"SELECT Name FROM Win32_Printer\", \"WQL\", 0);
var e = new Enumerator(query);
for         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 12:25

    If you'd like to avoid the need to use an explicit Enumerator every time you need to iterate over a collection object that needs one, you can define a little helper function like this:

    function forEach(collection, func) {
     for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
      func(e.item());
     }
    }
    

    Iteration over collections then becomes rather less clumsy:

    var queryResult = GetObject("winmgmts:").ExecQuery("SELECT Name, Status FROM Win32_Printer");
    
    // Enumerate WMI objects
    forEach (queryResult, function (oPrinter) {
    
        // Enumerate WMI object properties
        forEach (oPrinter.Properties_, function (p) {
            WScript.Echo(p.Name + ": " + p.Value);
        });
    });
    

提交回复
热议问题