因为MSIE 10的行为不同

ken*_*thc 1 javascript internet-explorer

以下茉莉花测试适用于PhantomJS或Chrome,但不适用于MSIE 10.

describe("utility", function () {

    var utility = {
        // { A: true, B: true } will become 'AB'
        CombineValues: function (splitValues) {
            var combined = '';
            for (item in splitValues) { // on IE, item is a function, not a string
                if (splitValues[item])  // on IE, this returns false all the time
                    combined = combined + item;
            }
            return combined;
        },

        // 'AB' will become { A: true, B: true }
        SplitValues: function (combined) {
            var splitValues = {};
            for (var i = 0; i < combined.length; i++) {
                splitValues[combined.charAt(i)] = true;
            }

            return splitValues;
        }
    };

    it('CombineValues(SplitValues()) should be idempotent', function () {
        // on MSIE, result is '' instead of 'ABC'
        expect(utility.CombineValues(utility.SplitValues('ABC'))).toBe('ABC');
    });
});
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

谢谢!

编辑:在IE上,项目显示:

function item() {
    [native code]
}
 {
    [prototype] :  function() {     [native code] } ,
    prototype : {...}
} 
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

在Internet Explorer中,window.item是一个功能.显然是一个不可覆盖的.

使用for (item in …)循环,您将隐式分配给该全局变量,该变量(以静默方式)在草率模式下失败.尝试添加一个"use strict";它应该抛出一个错误.

使用局部变量:

for (var item in splitValues) …
//   ^^^
Run Code Online (Sandbox Code Playgroud)

在严格模式下,分配给未声明的(在Chrome/Webkit中)全局变量也会失败,在草率模式下,您只需item使用该代码创建一个全局变量.