【问题标题】:Logical error! in Array insertion at specified position using strings逻辑错误!使用字符串在指定位置插入数组
【发布时间】:2021-07-23 12:35:51
【问题描述】:

我正在编写一个函数来提取单词中包含的单词的索引, 例如:4of Fo1r pe6ople g3ood th5e the2 这应该按顺序排列, 下面是代码,

function order(words){
    var result = []
    var sorting = words.split(' ').sort() 
    console.log(sorting);
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        console.log(valueHolder);
      result.splice((valueHolder-1),0,sorting[i]) //will pass the index here
    }
    console.log(result);
  }

但我得到了错误的输出:[ 'Fo1r', 'the2', '4of', 'g3ood', 'pe6ople', 'th5e' ] 我错过了什么吗,谁能帮我这个谢谢。 上面的array.splice(index,0,item) 只会在指定位置插入元素,并带有0

预期输出为:[ 'Fo1r', 'the2', 'g3ood', '4of', 'th5e','pe6ople' ]

【问题讨论】:

  • sorting[i].split('').sort() 会生成一个字符数组,如果我没有弄错的话,它会存储在temp 中。这怎么能用作parseInt的参数??
  • @TostMaster 我有目的地给出,因为 temp 总是给出初始索引值,因为我使用了排序,所以现在所有的数字都对齐了,通过使用 temp,我们将得到默认值作为初始索引项,这样我就可以获得真正的索引然后将其转换为整数

标签: javascript node.js arrays sorting


【解决方案1】:

您可以使用正则表达式,然后您可以解析 9 以上的数字。

正则表达式const r = /\d+/; 查找一位或多位数字。然后在排序方法a.match(r)中使用正则表达式,然后对结果数字进行解析和比较。

const str = '4of Fo1r pe6ople g3ood th5e no71w the2';

function order(words) {
  let result = [];
  let sorting = words.split(' ');
  const r = /\d+/;
  
  sorting.sort((a,b) => {
    return parseInt(a.match(r)) - parseInt(b.match(r));
  });
  console.log(sorting.join(' '));
}
order(str);

【讨论】:

  • @NilsKhaler,谢谢伙计,这也很好用
【解决方案2】:

问题是您的结果数组初始大小未设置,因此在循环期间拼接将无法正常工作。

简单修复:

words='4of Fo1r pe6ople g3ood th5e the2';

function order(words){
    var result = []
    var sorting = words.split(' '); 
    var result = new Array(sorting.length);
    console.log(result)
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      //console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        //console.log(valueHolder);
    result.splice(valueHolder-1,1,sorting[i]) //will pass the index here
   
    }
    console.log(result);
  }
  
order(words)

words='4of Fo1r pe6ople g3ood th5e the2';

function order(words){
    var result = []
    var sorting = words.split(' '); 
    var result = new Array(sorting.length);
   // console.log(result)
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      //console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        //console.log(valueHolder);
    result.splice(valueHolder-1,1,sorting[i]) //will pass the index here
   
    }
    console.log(result);
  }
  
order(words)

【讨论】:

    【解决方案3】:

    Array#splice 不是你应该在这里使用的正确的东西,而是使用索引将元素添加到所需的位置。

    function order(words) {
      var result = [];
      var sorting = words.split(" ").sort();
      for (let i = 0; i < sorting.length; i++) {
        var temp = sorting[i].split("").sort();
        var valueHolder = parseInt(temp);
        result[valueHolder - 1] = sorting[i];
      }
      console.log(result);
    }
    
    order("4of Fo1r pe6ople g3ood th5e the2");

    【讨论】:

    • @Aravinda KS 请检查这是否解决了您的问题,如果您有任何问题,请告诉我。
    【解决方案4】:

    这适用于所有场景。使用regex的更少和最简单的代码。

    解决方案

     function order(string) {
       var regex = /\d+/g;
       var matches = string.match(regex);        
       matches.sort(function(a, b){return parseInt(a)-parseInt(b)});
    
       var splittedArr = string.split(' ');
    
       var result = [];
       matches.forEach(item => {
          const findItem = splittedArr.find(a => a.includes(item));
          result.push(findItem);
       })
       console.log(result)
    }
    
    order('4of Fo1r pe6ople g3ood th5e the2') // your string
    order('77of Fo1r pe6ople g3ood th8e the2') // other string
    order('0of Fo1r pe6ople g4ood th8e the2') // other string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 2020-02-18
      相关资源
      最近更新 更多