user3331950
user3331950

Reputation: 119

Is JScript/WindowsScriptHost missing Array.forEach()?

I write JSCript and run it with the WindowsScriptHost.However, it seems to be missing Array.forEach().

['a', 'b'].forEach(function(e) {
    WSH.Echo(e);
});

Fails with "test.js(66, 2) Microsoft JScript runtime error: Object doesn't support this property or method".

That can't be right? Does it really lack Array.forEach()? Do I really have to use one of the for-loop-variants?

Upvotes: 3

Views: 1899

Answers (1)

rojo
rojo

Reputation: 24466

JScript uses the JavaScript feature set as it existed in IE8. Even in Windows 10, the Windows Script Host is limited to JScript 5.7. This MSDN documentation explains:

Starting with JScript 5.8, by default, the JScript scripting engine supports the language feature set as it existed in version 5.7. This is to maintain compatibility with the earlier versions of the engine. To use the complete language feature set of version 5.8, the Windows Script interface host has to invoke IActiveScriptProperty::SetProperty.

... which ultimately means, since cscript.exe and wscript.exe have no switches allowing you to invoke that method, Microsoft advises you to write your own script host to unlock the Chakra engine.

There is a workaround, though. You can invoke the htmlfile COM object, force it to IE9 (or 10 or 11 or Edge) compatibility, then import whatever methods you wish -- including Array.forEach(), JSON methods, and so on. Here's a brief example:

var htmlfile = WSH.CreateObject('htmlfile');
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');

// And now you can use htmlfile.parentWindow to expose methods not
// natively supported by JScript 5.7.

Array.prototype.forEach = htmlfile.parentWindow.Array.prototype.forEach;
Object.keys = htmlfile.parentWindow.Object.keys;

htmlfile.close(); // no longer needed

// test object
var obj = {
    "line1" : "The quick brown fox",
    "line2" : "jumps over the lazy dog."
}

// test methods exposed from htmlfile
Object.keys(obj).forEach(function(key) {
    WSH.Echo(obj[key]);
});

Output:

The quick brown fox
jumps over the lazy dog.

There are a few other methods demonstrated in this answer -- JSON.parse(), String.trim(), and Array.indexOf().

Upvotes: 6

Related Questions