js如何简洁地实现map [index] ++ [英] js how to implement map[index]++ concisely

查看:1043
本文介绍了js如何简洁地实现map [index] ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Array,我可以使用 array [index] ++

With Array, I can use array[index]++

但是使用Map,我只知道 map.set(index,map.get(index)+1)

But with Map, I only know map.set(index,map.get(index)+1)

我觉得它看起来很糟糕,如果 index 是一个长名称函数,我必须将它分成两行。

I think it looks bad, and if index is a long name function, I have to split it into two lines.

是否更简洁方法实现 map [index] ++

推荐答案

我只能这样做建议一个辅助函数,比如

I could only suggest a helper function, like

function update(map, key, fn) {
    return map.set(key, fn(map.get(key), key));
}

update(table, index, i=>i+1);

分配没有语法糖,因此也没有速记分配。

There is no syntactic sugar for assignments, and therefore no shorthand assignments either.

如果您的密钥是字符串,您可以使用 代理 ,使用合适的陷阱将更新伪装成属性访问。

If your keys are strings, you could employ a Proxy with suitable traps to disguise the update as a property access.

const mapMethods = {
    has: Function.prototype.call.bind(Map.prototype.has),
    get: Function.prototype.call.bind(Map.prototype.get),
    set: Function.prototype.call.bind(Map.prototype.set),
};
function asObject(map) {
    return new Proxy(map, mapMethods);
}

asObject(table)[index]++;

免责声明:请不要这样做。这太吓人了。

这篇关于js如何简洁地实现map [index] ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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