将Arrow函数转换为函数表达式

时间:2019-09-24 13:46:11

标签: javascript internet-explorer

我有一个带有地图对象的函数:

function xml_encode(s)
{
 return Array.from(s).map(c =>
 {
  var cp = c.codePointAt(0);
  return ((cp > 127) ? '&#' + cp + ';' : c);
 }).join('');
}

除了运行Internet Explorer 11时损坏了所有内容外,此方法非常有效。

我尝试使用函数表达式重写代码,但是未定义c

function xml_encode(s)
{
 return Array.from(s).map(function()
 {
  var cp = c.codePointAt(0);
  return ((cp > 127) ? '&#' + cp + ';' : c);
 }).join('');
}

不幸的是,这必须是一个面向公众的功能,并且需要目前支持IE11。如何重写此功能以与IE11一起使用?

3 个答案:

答案 0 :(得分:0)

您缺少函数的参数,所以请尝试

function xml_encode(s) {
  return Array.from(s).map(function(c) {
    var cp = c.codePointAt(0);
    return ((cp > 127) ? '&#' + cp + ';' : c);
  }).join('');
}

答案 1 :(得分:0)

您缺少匿名功能的c参数。

function xml_encode(s)
{
  return Array.from(s).map(
    function(c) {
      //use charCodeAt for IE or use a polyfill
      //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt#Polyfill
      var cp = c.codePointAt(0); 
      return ((cp > 127) ? '&#' + cp + ';' : c);
    }
  ).join('');
}

奖金: 您可能希望使用s.split('')而不是Array.from(s)以获得更好的性能和浏览器支持。例如,每个浏览器都支持String.prototype.split,而IE中不支持Array.from。在我的PC上,split在Chrome上也快30%,在FF上快80%。

答案 2 :(得分:0)

尝试如下修改您的代码(该函数缺少参数):

function xml_encode(s) {
  return Array.from(s).map(function (c) {
    var cp = c.codePointAt(0);
    return cp > 127 ? '&#' + cp + ';' : c;
  }).join('');
}

因为您使用的是Array.from和codePointAt函数,所以它们不支持IE浏览器。要在IE浏览器中使用它们,我们需要在使用此功能之前添加相关的popyfill。

如下所示的代码(我已经创建了一个示例来对其进行测试,它对我而言效果很好。):

    // Production steps of ECMA-262, Edition 6, 22.1.2.1
    if (!Array.from) {
        Array.from = (function () {
            var toStr = Object.prototype.toString;
            var isCallable = function (fn) {
                return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
            };
            var toInteger = function (value) {
                var number = Number(value);
                if (isNaN(number)) { return 0; }
                if (number === 0 || !isFinite(number)) { return number; }
                return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
            };
            var maxSafeInteger = Math.pow(2, 53) - 1;
            var toLength = function (value) {
                var len = toInteger(value);
                return Math.min(Math.max(len, 0), maxSafeInteger);
            };

            // The length property of the from method is 1.
            return function from(arrayLike/*, mapFn, thisArg */) {
                // 1. Let C be the this value.
                var C = this;

                // 2. Let items be ToObject(arrayLike).
                var items = Object(arrayLike);

                // 3. ReturnIfAbrupt(items).
                if (arrayLike == null) {
                    throw new TypeError('Array.from requires an array-like object - not null or undefined');
                }

                // 4. If mapfn is undefined, then let mapping be false.
                var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
                var T;
                if (typeof mapFn !== 'undefined') {
                    // 5. else
                    // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
                    if (!isCallable(mapFn)) {
                        throw new TypeError('Array.from: when provided, the second argument must be a function');
                    }

                    // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
                    if (arguments.length > 2) {
                        T = arguments[2];
                    }
                }

                // 10. Let lenValue be Get(items, "length").
                // 11. Let len be ToLength(lenValue).
                var len = toLength(items.length);

                // 13. If IsConstructor(C) is true, then
                // 13. a. Let A be the result of calling the [[Construct]] internal method 
                // of C with an argument list containing the single item len.
                // 14. a. Else, Let A be ArrayCreate(len).
                var A = isCallable(C) ? Object(new C(len)) : new Array(len);

                // 16. Let k be 0.
                var k = 0;
                // 17. Repeat, while k < len… (also steps a - h)
                var kValue;
                while (k < len) {
                    kValue = items[k];
                    if (mapFn) {
                        A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
                    } else {
                        A[k] = kValue;
                    }
                    k += 1;
                }
                // 18. Let putStatus be Put(A, "length", len, true).
                A.length = len;
                // 20. Return A.
                return A;
            };
        }());
    }

    /*! https://mths.be/codepointat v0.2.0 by @mathias */
    if (!String.prototype.codePointAt) {
        (function () {
            'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
            var defineProperty = (function () {
                // IE 8 only supports `Object.defineProperty` on DOM elements
                try {
                    var object = {};
                    var $defineProperty = Object.defineProperty;
                    var result = $defineProperty(object, object, object) && $defineProperty;
                } catch (error) { }
                return result;
            }());
            var codePointAt = function (position) {
                if (this == null) {
                    throw TypeError();
                }
                var string = String(this);
                var size = string.length;
                // `ToInteger`
                var index = position ? Number(position) : 0;
                if (index != index) { // better `isNaN`
                    index = 0;
                }
                // Account for out-of-bounds indices:
                if (index < 0 || index >= size) {
                    return undefined;
                }
                // Get the first code unit
                var first = string.charCodeAt(index);
                var second;
                if ( // check if it’s the start of a surrogate pair
                    first >= 0xD800 && first <= 0xDBFF && // high surrogate
                    size > index + 1 // there is a next code unit
                ) {
                    second = string.charCodeAt(index + 1);
                    if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
                        // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
                        return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
                    }
                }
                return first;
            };
            if (defineProperty) {
                defineProperty(String.prototype, 'codePointAt', {
                    'value': codePointAt,
                    'configurable': true,
                    'writable': true
                });
            } else {
                String.prototype.codePointAt = codePointAt;
            }
        }());
    }

更多详细信息,请检查Array.from() methodcodePointAt() method