简体   繁体   中英

Using splice with an array of strings

I have an array of strings.

I want to ckhek if in the array there are strings of blanks only and remove them.

To this purpose I've written the following code that trims the blanks and should then delete the elemens with length = 0.

The trim works, the string of blanks are actually of 0 legth (I check this with the alert) but the elements are not removed from the array.

Of course, searchterms is the array.

for (var i=0;i<searchterms.length;i++)
        {       
        searchterms[i]=searchterms[i].trim();
        alert(searchterms[i]+" - "+searchterms[i].toString().length);
        if  (searchterms[i].toString().length = 0)
            {
            searchterms.splice(i,1);
            }
        }   

The same happens if I use the following code instead:

for (var i=0;i<searchterms.length;i++)
        {       
        tempterm=searchterms[i].trim();
        alert(tempterm+" - "+tempterm.toString().length);
        if  (tempterm.toString().length = 0)
            {
            searchterms.splice(i,1);
            }
        }   

Thanks in advance.

if  (searchterms[i].toString().length = 0)

You are performing an assignment( = ) in the if statement where it should be comparison(equality operator == ) instead.

if  (searchterms[i].toString().length == 0)

Another problem is that splice modifies the original array. So the indexes of elements at each iteration will change if a blank element is encountered.

This can also be done in a more concise way using Array.prototype.filter

var searchTerms = ['asdf', '', 'ed', '   ', 'd##'];    
var newTerms = searchTerms.filter(function(e) {
    return e.trim().length !== 0;
});

console.log(newTerms);

jsFiddle Demo

var temp = Array();
var k=0;

for (var i=0;i<searchterms.length;i++)
{       
         if((searchterms[i].trim())!="" && searchterms[i].length>0)
         {
           temp[k] = searchterms[i];
           k++;
         }

}  

Temp will contain the new arrray

Try this

var i = 0;
while (i < searchterms.length)
{
    if (searchterms[i].trim().length == 0) searchterms.splice(i, 1);
    i++;
}

try this

Description:

Javascript array splice() method changes the content of an array, adding new elements while removing old elements. Syntax:

array.splice(index, howMany, [element1][, ..., elementN]);

Here is the detail of parameters:

**index :** Index at which to start changing the array.

**howMany :** An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.

element1, ..., elementN : The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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