简体   繁体   English

具有多个参数的函数的JavaScript缓存返回值

[英]JavaScript cache return value of a function with more than one parameter

I'm going through John Resig's snippets on advanced JavaScript . 我正在研究John Resig的有关高级JavaScript的片段 On #19 he mentions a method to cache the return value of a function. #19中,他提到了一种缓存函数返回值的方法。 What's the best way to cache the return value of a function that has more than one parameter? 缓存具有多个参数的函数的返回值的最佳方法是什么?

There has to be a much better way than stringify-ing the recieved arguments and using that as the key for the cache object: 除了串化接收到的参数并将其用作缓存对象的键之外,还有一种更好的方法:

function $$(selector, el) {
    var cacheKey = JSON.stringify(arguments);
    if ($$.cache[cacheKey]) return $$.cache[cacheKey];

    return ($$.cache[cacheKey] = NodeListToArray( (el || document).querySelectorAll(s) ));
}
$$.cache = {};

You could use a custom hash function that can operate on objects. 您可以使用可以对对象进行操作的自定义哈希函数。 But hash functions cause collisions and would require significantly more code than your simple example. 但是哈希函数会导致冲突,并且比简单的示例需要更多的代码。

Or you could make the cache n-dimensional, where n is the number of arguments. 或者,您可以使高速缓存为n维,其中n为参数数。 So essentially this: 所以本质上是这样的:

function $$(selector, el) {
    if ($$.cache[selector] && $$.cache[selector][el])
        return $$.cache[cacheKey][el];
    // etc.

That assumes that both selector and el are able to be used as object keys. 假定选择器和el都可以用作对象键。 You may need to stringify them in another manner. 您可能需要以其他方式对它们进行分类。

Just consider an array element, 只要考虑一个数组元素,

JSON (JavaScript Object Notation) works with generic platform, so for easy use you must create a function for your use, JSON(JavaScript对象表示法)可在通用平台上使用,因此,为了易于使用,您必须创建一个要使用的函数,

Here, $$.cache[0] is your easy way after reading the cachekey , 在这里, $$.cache[0]是读取cachekey之后的简便方法,

If we make thing more easy, we might have security problem later. 如果我们使事情变得简单,那么以后可能会遇到安全问题。

I hope this will satisfy your requirement :) 我希望这可以满足您的要求:)

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

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