2016-04-08 69 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()