Remove Whitespace-only Array Elements

后端 未结 8 914
悲&欢浪女
悲&欢浪女 2020-12-08 17:30

Since using array.splice modifies the array in-place, how can I remove all whitespace-only elements from an array without throwing an error? With PHP we have preg_grep but I

8条回答
  •  悲&欢浪女
    2020-12-08 18:04

    You removed an item from the array which reduced the array's length. Your loop continued, skipped some indexes (those which were down-shifted into the removed index), and eventually attempted to access an index outside of the new range.

    Try this instead:

    var src = ["1"," ","2","3"];
    var i = src.length;    
    while(i--) !/\S/.test(src[i]) && src.splice(i, 1);
    console.log(src);

提交回复
热议问题