【问题标题】:Why array.prototype.map.call(..) doesn't work in case prototype framework using there?为什么在使用原型框架的情况下 array.prototype.map.call(..) 不起作用?
【发布时间】:2013-11-28 00:44:14
【问题描述】:

如果我在没有原型框架的情况下使用此代码:

if (XMLHttpRequest.prototype.sendAsBinary) return;
        XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
            function byteValue(x) {
                return x.charCodeAt(0) & 0xff;
            }
            console.log(Array.prototype.map);
            var ords = Array.prototype.map.call(datastr, byteValue);
            var ui8a = new Uint8Array(ords);
            this.send(ui8a.buffer);
        }

日志返回:

function map() { [native code] } 

如果包含原型 js 框架,则日志返回这个:

function collect(iterator, context) {
    iterator = iterator || Prototype.K;
    var results = [];
    this.each(function(value, index) {
      results.push(iterator.call(context, value, index));
    });
    return results;
  } 

同时报错:

Uncaught TypeError: Object [object String] has no method 'each' prototype.js:864
collect prototype.js:864
XMLHttpRequest.sendAsBinary jquery.filedrop.js:309
send jquery.filedrop.js:215

无论如何,jQuery 也在使用。

jQuery.noConflict();

为什么我在原型框架开启的情况下无法运行原生地图功能?

【问题讨论】:

  • datastr 是一个数组吗? (答案是否定的。)原型用它自己的方法覆盖Array.prototype.map。所述方法似乎不适用于字符串。
  • 我猜你可以通过将字符串设为数组datastr.split("")来“修复”它,此时你可以简单地执行var ords = datastr.split("").map(byteValue)
  • datastr是图片字符串数据。
  • var ords = datastr.split("").map(byteValue) 似乎工作

标签: javascript jquery map prototypejs prototype


【解决方案1】:

当您包含prototypejs 时,Array.prototype.map 将替换为prototypejs 方法。新方法假定它将始终在数组上调用,这会导致您的用例失败,因为您是在字符串上调用它。

解决方法是将字符串转换为数组。

var ords = Array.prototype.map.call(datastr.splt(""), byteValue);

然后可以简化为:

var ords = datastr.splt("").map(byteValue);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    相关资源
    最近更新 更多