我試圖遍歷一個字串陣列,對于該陣列中的每個元素(字串),將“_”下劃線字符后的字符更改為“*”字符。字串是不可變的,因此將所有這些都推送到一個新陣列中。
當直接針對下劃線進行替換時,該鏈按預期執行:
const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure']
const t2 = t1.map(e => e.replace(e[e.indexOf('_')], '*'))
// Output: ['underscore*case', 'first*name', 'some*variable', 'calculate*age', 'delayed*departure']
但是在追求實際預期功能的那一刻,修改下劃線后面的字符 - 輸出幾乎變得瘋狂,“*”在每個字串中以隨機間隔出現。在以下兩種嘗試中:
const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure']
const t2 = t1.map(e => e.replace(e[e.indexOf('_') 1], '*'))
// Output: ['unders*ore_case', 'first_*ame', 'some_*ariable', 'c*lculate_age', '*elayed_departure']
以及,在一些絕望之后,手動輸入索引,如下所示:
const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure']
const t2 = t1.map(e => e.replace(e[5], '*'))
// Output: ['under*core_case', 'first*name', 'some_*ariable', 'ca*culate_age', 'd*layed_departure']
實驗表明,出于某種原因,意外行為,特別是在最后兩個元素中 - 僅當手動指定的索引值出于某種原因超過或等于 5 時才會出現?
為什么會這樣?
在嘗試各種回圈方法并在鏈接之外分解每個操作幾個小時后,我在使用替換方法時不斷回傳相同的結果,無論發生在哪里 - 并且不得不使用涉及切片方法和模板文字的解決方法。
uj5u.com熱心網友回復:
下劃線后面的字符也可能出現在字串的較早位置,在這種情況下,replace呼叫將找到該出現并替換它。
因此,例如,以“calculate_age”,e[indexOf("_") 1]將評估為“A”(的“年齡”),但replace會發現一個“a”在字串的開頭,并更換是一個帶有星號。
相反,為此使用正則運算式:
const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure'];
const t2 = t1.map(e => e.replace(/_./g, '_*'));
console.log(t2);
正則運算式中的點是通配符。所以無論它是什么(換行符除外),它都會被替換(連同下劃線)用“_*”。
至于你寫的:
字串是不可變的,因此將所有這些都推送到一個新陣列中。
是的,字串是不可變的,但陣列是可變的,因此您可以決定用替換來替換該陣列中的所有字串。然后你改變陣列,而不是字串。
話雖如此,創建一個新陣列很好(并且很好的函式式編程)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404655.html
標籤:
下一篇:如何在C中檢查空字符指標
