尽量不要添加数组中已有的元素

try to not add the elements already in the array

function neighbor(color_indices) {
    var neighbor_face = [];
    var neighbor_index_temp = [];
    //initialize to the given length 
    var color_indices_length = color_indices.length; 
    for (var i = 0; i < color_indices_length; i++) {    
        if (color_indices[i] % 2 == 0 ) {
            if (color_indices[i] % 10 == 8) {
                neighbor_index_temp[0] = (color_indices[i]) + 1; 
                neighbor_index_temp[1] = (color_indices[i]) - 17;
                neighbor_index_temp[2] = (color_indices[i]) - 19;
                //check if it is in the array
                for (var k = 0; k < 3; k++){
                   if ($.inArray(neighbor_index_temp[k],color_indices) != -1){
                        color_indices.push(neighbor_index_temp[k]);
                    }
                 }

输入:color_indices 将是一个全局变量数组。我正在尝试将 neighbor_index_temp 推到 color_indices。我试图实施 $.inArray 但它似乎不起作用。有什么建议吗?

谢谢!

您可以使用 indexOf 来实现这一点。即

if(color_indices.indexOf(neighbor_index_temp[k]) == -1) {
    // value neighbor_index_temp[k] is not in color_indices array
}

编辑:$.inArray 可能与 indexOf 的作用相同,在这种情况下,您可能希望将 '!= -1' 更改为 '== -1'