2016-04-08 74 views
2

我写JSCript并运行它与WindowsScriptHost.However,它似乎缺少Array.forEach()。JScript/WindowsScriptHost是否缺少Array.forEach()?

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

未能通过“test.js(66,2)Microsoft JScript运行时错误:对象不支持此属性或方法”。

那是不对的?它真的缺乏Array.forEach()吗?我真的必须使用其中一个for循环变体吗?

回答

2

JScript使用JavaScript功能集as it existed in IE8。即使在Windows 10中,Windows Script Host也仅限于JScript 5.7。这MSDN documentation解释:

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 .

......这最终意味着,因为cscript.exewscript.exe没有开关让您可以调用该方法,Microsoft建议您编写自己的脚本宿主解锁查克拉引擎。

虽然有一个解决方法。您可以调用COM对象,强制它与IE9(或10或11或Edge)兼容,然后导入任何您希望的方法 - 包括Array.forEach(),JSON方法等。这里有一个简单的例子:

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

输出:

The quick brown fox
jumps over the lazy dog.

还有一些其他的方法demonstrated in this answer - JSON.parse()String.trim()Array.indexOf()