簡體   English   中英

從javascript數組中刪除元素會導致問題

[英]Removing an element from a javascript array causing issues

所以我對為什么此方法不起作用有些困惑。 我正在嘗試刪除數組中的所有空字符串,它一直在給我一個只是一個空字符串的數組。 有任何想法嗎?

function splitNames(){
    var names = document.getElementById("1").value.split("\n");
    for(var i = 0; i<=names.length; i++){
        if(names[i]==""){
            names = names.splice(i, 1);
            console.log(names);
        }
    }
    console.log(names);
}

順便說一下,字符串看起來像這樣。

你好

你好

(刪除這個)

你好

等等

(刪除這個)

(刪除這個)

等等

數組出現在此[“ Hi”,“ Hello”,“”,...]

也許最簡單的方法是使用filter功能並搜索真實值。 默認情況下,空字符串為false。

filter()方法創建一個新數組,其中所有元素都通過了由提供的函數實現的測試。

 var strings = ["zebras", "trees", "forests", "", "hi", "wizards", "", "", "lizards"]; strings = strings.filter((e) => e); console.log(strings); 

請務必注意,默認情況下,空字符串為false。 但是,僅包含空格字符的字符串為true。 在這種情況下,我的示例將不起作用,您將必須執行此操作

strings.filter((e) => e.trim());

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 function splitNames(){ // var names = document.getElementById("1").value.split("\\n"); var names = "Hi\\nHello\\n \\nGoodBye".split("\\n"); var filteredNames = names.filter(function(item){ return item.trim() !== ""; });//filter return filteredNames; }//splitNames() console.log( splitNames() ); 

創建一個新數組,然后推送您所需的內容。

function splitNames(){
    var names = document.getElementById("1").value.split("\n");
    var newArr = [];

    for(var i = 0; i<=names.length; i++){
        if(names[i]){
            newArr.push(names[i]);
        }
    }

    return newArr.join('\n');
    //console.log(names);

}

試試吧:

function splitNames(){

    var names = document.getElementById("1").value.split("\n");
    var newArr = names.filter(function(name){
        return name!=="";
    });

    return newArr;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM