如何返回不在Javascript地图中的元素数组?(How do I return an array of elements NOT in a Javascript map?)

系统教程 行业动态 更新时间:2024-06-14 16:57:18
如何返回不在Javascript地图中的元素数组?(How do I return an array of elements NOT in a Javascript map?)

我有一个Javascript对象:

var errorMap = { 100: 'You must enter a name.', 200: 'You must enter an address.', 300: 'You must enter a DOB.' }

在我的代码的另一部分,我收到一组错误代码:

var errorCodes = [100, 200, 500, 600];

我想要做的是将errorCodes数组与errorMap对象的键进行比较,并返回errorMap 没有相应键的所有错误代码。 在这种情况下,我想得到这个:

[500, 600]

我该怎么做呢? 我可以访问jQuery。

I have a Javascript object:

var errorMap = { 100: 'You must enter a name.', 200: 'You must enter an address.', 300: 'You must enter a DOB.' }

In another part of my code, I am receiving an array of error codes:

var errorCodes = [100, 200, 500, 600];

What I'd like to do is compare the errorCodes array to the errorMap object's keys and return all error codes that do not have a corresponding key in errorMap. In this case, I would like to get this back:

[500, 600]

How do I do this? I have access to jQuery.

最满意答案

适用于现代浏览器的Javascript(适用于带有填充程序的旧版浏览器)

var missing = [100, 200, 500, 600].filter(function(v){ return !errorMap.hasOwnProperty(v) }); //missing = [500, 600]

jQuery,以防需要遗留浏览器支持,并且不接受填充:

var missing = $.grep( [100, 200, 500, 600], function(v){ return !errorMap.hasOwnProperty(v) }); //missing = [500, 600]

Javascript for modern browsers (works in older browsers with a shim)

var missing = [100, 200, 500, 600].filter(function(v){ return !errorMap.hasOwnProperty(v) }); //missing = [500, 600]

jQuery in case legacy browser support is required and shim is not acceptable:

var missing = $.grep( [100, 200, 500, 600], function(v){ return !errorMap.hasOwnProperty(v) }); //missing = [500, 600]

更多推荐

本文发布于:2023-04-12 20:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a2cd109594cf9be9743e40077881e257.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   图中   元素   Javascript   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!