简体   繁体   English

关于 JavaScript 数组原型

[英]Regarding with JavaScript array prototype

I have recently read tutorial associated with JavaScript from this page , I tried some piece of code but i didn't understand some logic.我最近从这个页面阅读了与 JavaScript 相关的教程,我尝试了一些代码,但我不明白一些逻辑。 Below is author code.下面是作者代码。

function itself:函数本身:

var lz="";
lz.memo = function (fn) {
var cache = {};
return function () {
    var key = [].join.call(arguments, '§') + '§';
    if (key in cache) {
        return cache[key];        }
    return cache[key] = fn.apply(this, arguments);
  };
};

and its execution及其执行

 var foo = 1;
function bar(baz) {
    return baz + foo;
}
var cached = lz.memo(bar);
console.log(cached(1));
foo += 1;
console.log(cached(1)); //2

But if I change但如果我改变

var key = [].join.call(arguments, '§') + '§';

to

var key=arguments[0];

it also works (Caching works).它也有效(缓存有效)。 What is the purpose here the author used作者在这里使用的目的是什么

var key = [].join.call(arguments, '§') + '§';

Thank for attention!感谢关注! Here is CODEPEN of code这是代码的CODEPEN

it also works (Caching works)它也有效(缓存有效)

Only because you called it with just one argument.只是因为你只用一个参数调用它。 (And it didn't quite work the same way, the cache key will be missing the § on the key that the original code had.) (而且它的工作方式并不完全相同,缓存键将缺少原始代码所具有的键上的§ 。)

What is the purpose here the author used作者在这里使用的目的是什么

They're creating a string with all of the arguments you supply joined together with § between them and § at the end, like this:他们创造了所有的您提供加入连同参数字符串§它们之间§末,就像这样:

 function foo() { return [].join.call(arguments, '§') + '§'; } console.log(foo(1)); // 1§ console.log(foo(1, 2)); // 1§2§ console.log(foo("a", "b", "c")); // a§b§c§

They're doing it because arguments is array-like , but it isn't an array, and so it doesn't have the join method from Array.prototype .他们这样做是因为arguments类似数组的,但它不是数组,因此它没有来自Array.prototypejoin方法。

There's actually no reason for the temporary array they create, you can just call join directly:他们创建的临时数组实际上没有任何理由,您可以直接调用join

return Array.prototype.join.call(arguments, '§') + '§';

Another opton is to convert arguments to an actual array:另一个选项是将arguments转换为实际数组:

return Array.prototype.slice.call(arguments).join('§') + '§';

Or in ES2015 (or with a shim):或者在 ES2015 中(或使用垫片):

return Array.from(arguments).join('§') + '§';

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

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