简体   繁体   English

从JavaScript ES5中的数组获取未定义的项目

[英]Get not undefined items from array in javascript ES5

I'm retrieving a list of items from the server side in JSON format and storing them into a javascript array. 我正在以JSON格式从服务器端检索项目列表,并将它们存储到javascript数组中。 The list of items retrieved from the server can contain duplicate elements but I need that the javascript array only contains unique elements. 从服务器检索的项目列表可以包含重复元素,但是我需要javascript数组仅包含唯一元素。

In order to do that, I'm using the id field from each item (an integer value) as the array index, so that I can check if the item is already in the array by checking the array value at that position. 为此,我将每个项目的id字段(一个整数值)用作数组索引,以便可以通过检查该位置的数组值来检查该项目是否已在数组中。

Due to that the resulting array can contain only elements at indexes 0 and 5 (just an example), and I'm facing problems when iterating it with jQuery's $.each() method, because it traverses every array position from 0 to 5, being undefined the values in positions 1-4. 由于生成的数组只能包含索引0和5的元素(仅作为示例),并且在使用jQuery的$.each()方法对其进行迭代时遇到了问题,因为它遍历从0到5的每个数组位置undefined位置1-4中的值。

I can of course just check that the item is not undefined when traversing, but I would like to know if there is some native or straightforward way to obtain the values of the array from those positions that aren't undefined. 我当然可以在遍历时检查项目是否未定义,但是我想知道是否存在一些本机或直接的方法来从那些未定义的位置获取数组的值。

var x = [];
x[0] = "some value";
x[5] = "another value";

$.each(x, function(index, value) {
   console.log(index + " - " + value);    
});

// This results in:
// 0 - some value
// 1 - undefined
// 2 - undefined
// 3 - undefined
// 4 - undefined
// 5 - another value

I also accept suggestions to perform this process in a different way, instead of using the item id as the array index to check uniqueness. 我也接受以其他方式执行此过程的建议,而不是使用item id作为数组索引来检查唯一性。

Use an object instead: 改用一个对象:

 var x = {}; x[0] = "some value"; x[5] = "another value"; $.each(x, function(key, value) { console.log(key + " - " + value); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Just use the array's own forEach , which skips non-existent entries: 只需使用数组自己的forEach ,它会跳过不存在的条目:

 var x = []; x[0] = "some value"; x[5] = "another value" x.forEach(function(value, index) { console.log(index + " - " + value); }); 

Note that the order of the parameters to the callback is reversed. 请注意,回调参数的顺序相反。

If you really want to use $.each , do a check to see if the property exists: 如果您确实要使用$.each ,请检查该属性是否存在:

 var x = []; x[0] = "some value"; x[5] = "another value" $.each(x, function(index, value) { if (x.hasOwnProperty(index)) { console.log(index + " - " + value); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

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

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