在数组中替换/删除空条目

4

我有这个数组:[home, info, mail,,,, something, stuff, other]

但是我想删除或替换,,,

我尝试了:allIDs.replace(",,", ",");,但这似乎不适用于数组。

数组中存在空条目的原因是:

$(document).find('DIV').each(function(){
    allIDs.push(this.id); })

我正在索引所有 DIV 的 ID 名称,以检查是否存在重复,并重新命名当前生成的 DIV ID。
或者我想要只使用 find() 查找已定义 ID 的 DIV。
6个回答

2
这个非常有效:
theArray = theArray.filter(function(e) { return e; });

2
尝试使用$('div[id]')代替。它将选择所有定义了id属性的div元素。

1

将您的id收集更改为以下内容...

var allIDs = $(document).find('DIV')
                        .map(function(){ return this.id || undefined })
                        .toArray();

如果
标签上没有ID,将返回undefined,并且不会将任何内容添加到结果数组中。

0
你想要的是从数组中删除空值,而不是用,替换,,,我猜测。

请尝试这里


0
尝试仅获取已定义ID的
元素:
$(document).find('div[id]').each(function(){
    allIDs.push(this.id); });
});

但是如果你想清空数组:

allIDs = clean_up(allIDs);

function clean_up(a){
    var b = []
    for(i in a) if(a[i] && a[i].length) a.push(a[i]);
    return a;
}

0
在JavaScript中,你不能仅仅通过删除数组中的',,,'来解决问题。
你是指这个数组['home', 'info', '', '', '', '', 'mail', 'something', 'stuff', 'other']吗?
假设有一些空字符串,你想要将它们删除。
你可以使用一个简单的JavaScript函数:
allIDs = ["home", "info", "", "", "", "", "mail", "something", "stuff", "other"];

remove_empty_str = function(arr) {
  new_array = [];
  for (ii = 0, len = arr.length; ii < len; ii++) {
    item = arr[ii];
    if (item !== "" || item !== null || item !== (void 0)) {
      new_array.push(item);
    }
  }
  return new_array;
};

newIDs = remove_empty_str(allIDs);

alert(newIDs);

我认为在进行任何jQuery输出之前,处理数组是更好的实践。

您还可以在其他应用程序中重复使用remove_empty_str()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接