如何返回不在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]更多推荐
发布评论