将Arrow函数转换为函数表达式 [英] Convert Arrow function to function expression

查看:65
本文介绍了将Arrow函数转换为函数表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function with a map object:

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

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

This has worked great except it has broken everything when running Internet Explorer 11.

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

I tried to rewrite the code using a function expression however I get a c is not defined:

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

不幸的是,这需要成为一个面向公众的功能,需要暂时支持IE11.如何重写此功能以与IE11一起使用?

Unfortunately this needs to be a public-facing function and I am required to support IE11 for now. How do I rewrite this function to work with IE11?

推荐答案

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

Try to modify your code as below (you are missing an argument in the function):

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.

Since, you are using Array.from and codePointAt function, they don't support IE Browser. To use them in the IE browser, we need to add the related popyfill before using this function.

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

Polyfill code as below (I have created a sample to test it, it works well on my side.):

    // 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()方法

More detail information, please check the Array.from() method and the codePointAt() method

这篇关于将Arrow函数转换为函数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆