繁体   English   中英

尝试在 JavaScript 中实现 Python 风格的 len()

[英]Trying to Implement Python-Style len() in JavaScript

我已经阅读了很多关于 JavaScript 中的call()bind()的内容,特别是这篇MDN 文章中创建快捷方式部分。

我正在尝试在 JS 中实现以下 Python 风格的函数:

var arr = [1,2,3];
len(arr); // 3

我确实意识到这是一个人为的例子,但我试图围绕这些方法。 这是我如何实施它:

var len = Function.prototype.call.bind( Array.prototype.slice.length );
len([1,2,3]);

当我运行它时,我得到:

len([1,2,344])
^

TypeError: len is not a function
    at Object.<anonymous> (/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 11.js:2:1)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

我在这里缺少什么来理解它是如何工作的?

当您在代码中设置变量len ,实际上是将len设置为函数Function.prototype.call的副本,并带有Array.prototype.slice.lengththis (上下文)。

我认为您误解了 bind() 的使用。 假设我有一个函数len

var len = function() {
    return this.length;
};

并且您想获取数组的长度:

len.call([1,2,3]);

在这种情况下, len中的this是数组[1,2,3] ,因为我们使用call来提供this 假设我们想将该数组永久绑定到该函数并将其存储在一个我们可以随时使用的变量中:

var myArrayLen = len.bind([1,2,3]);

现在, myArrayLen 基本上是 len 的副本,与[1,2,3]this永久绑定。 如果我们调用它,它返回 3。

在您的示例中, Array.prototype.slice.length实际上是函数Array.prototype.slice的长度,它对应于可以传递给函数的参数数量

没有内置的 length() 函数,因此按照您(诚然)人为设计的示例,我们只需要创建一个提供长度的函数,将其添加到数组原型中,然后使用Function.prototype.apply.bind();绑定它Function.prototype.apply.bind();

Array.prototype.len = function () { return this.length; };
var len = Function.prototype.apply.bind(Array.prototype.len);
len([1,2,3]); // 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM