【问题标题】:Javascript string replace one at a time and add to arrayJavascript字符串一次替换一个并添加到数组
【发布时间】:2021-04-10 22:18:03
【问题描述】:

所以我编写了一个代码来替换某些单词并生成最可能相关的术语。

例如:'st vin st vin' 必须给我数组 [ 'st vin st vin', '圣文圣文', '圣文圣文', '英石。 vin st vin', '英石。文圣。文', ]

const getRelatedTerms =async searchTerm =>{
  const likeTerms=[
    {good:'st', bad:'saint'},
    {good:'st', bad:'st.'},

    {good:'st.', bad:'saint'},
    {good:'st.', bad:'st'},

    {good:'saint', bad:'st.'},
    {good:'saint', bad:'st'}
  ]
  const arr=[];

for(let i=0; i< likeTerms.length; i++){
  let temp =searchTerm;
  let item = likeTerms[i]; 
   while(temp.includes(item.good)){
      temp = temp.replace(item.good,item.bad);
      arr.push(temp)
    }
}

}

我不确定这里的确切问题是什么。它抛出 CALL_AND_RETRY_LAST 分配失败 - JavaScript heap out of memory 错误

【问题讨论】:

    标签: javascript arrays string loops


    【解决方案1】:

    您的代码处于无限循环中。

    作为一个无限循环的例子,考虑:你的输入字符串是"st vin"

    您将"st" 替换为"st.",因此您的字符串变为"st. vin"

    然后检查"st. vin" 是否包含"st",它确实存在,然后再次替换它,现在生成字符串"st.." vin。这将永远重复。

    有几种方法可以解决这个问题。最简单的可能是改用.replaceAll()

    const getRelatedTerms = searchTerm =>{
      const likeTerms=[
        {good:'st', bad:'saint'},
        {good:'st', bad:'st.'},
    
        {good:'st.', bad:'saint'},
        {good:'st.', bad:'st'},
    
        {good:'saint', bad:'st.'},
        {good:'saint', bad:'st'}
      ]
      const arr = [];
      for(let i = 0; i < likeTerms.length; i++) {
        const item = likeTerms[i];
        arr.push(searchTerm.replaceAll(item.good, item.bad));
       }
       return arr;
    }
    

    还要注意您的函数的另外两个错误:您使用了async 函数声明,但您的函数是同步的,因此您不需要async。你也不要在最后返回arr,这是在上面的代码中完成的。

    额外的重构

    如果您愿意,您还可以继续简化功能。您可以将好的和坏的声明移到函数之外,因为似乎不需要每次都重新创建它。您可以将循环更改为返回数组的映射,这样您就可以在一行中创建函数。如果一个函数只有一个表达式,您可以删除包装 {} 并删除 return 语句。这是使用“胖箭头”函数的好处 (=&gt;)

    const likeTerms = [
      {good:'st', bad:'saint'},
      {good:'st', bad:'st.'},
    
      {good:'st.', bad:'saint'},
      {good:'st.', bad:'st'},
    
      {good:'saint', bad:'st.'},
      {good:'saint', bad:'st'}
    ];
    
    const getRelatedTerms = searchTerm => likeTerms.map(
      ({ good, bad }) => searchTerm.replaceAll(good, bad)
    );
    

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2011-07-01
      • 2023-04-06
      • 2020-09-10
      • 2012-01-01
      • 2011-12-01
      • 2013-12-05
      相关资源
      最近更新 更多