1
var arr = [ 4, "Pete", "test", 8, "John", "", "test" ];

如何从此数组中删除值测试和空字符串?最好的方法是什么?

4

4 回答 4

6
var arr = [ 4, "Pete", "test", 8, "John", "", "test" ]; 
var l = arr.length;

while( l-- ) {
    if( arr[l] === "test" || arr[l] === "" ) {
        arr.splice(l, 1);
    }
}

//> arr
//[4, "Pete", 8, "John"]
于 2012-08-07T11:34:46.957 回答
2

替代方案:过滤器

var arr = [ 4, "Pete", "test", 8, "John", "", "test" ]
           .filter(function(v){return String(v).length && v !== 'test';});
//=> arr = [4, "Pete", 8, "John"];
于 2012-08-07T11:45:45.433 回答
1

如果您想删除单个项目,请检查它可能会对您有所帮助

http://jsfiddle.net/HWKQY/

于 2012-08-07T11:45:32.587 回答
0

如果您知道数组中项目的索引,则可以轻松使用 splice

arr.splice(索引,多少)

howmany=要删除的项目数

http://www.w3schools.com/jsref/jsref_splice.asp

于 2012-08-07T11:45:50.870 回答