【问题标题】:Unable to get array to display results of a nested for loop correctly无法获取数组以正确显示嵌套 for 循环的结果
【发布时间】:2020-10-15 08:35:06
【问题描述】:

我正在尝试完成一个代码战练习,您只需根据字符串中的数字按顺序返回一串单词。

示例:

order("is2 Thi1s T4est 3a") // should return "Thi1s is2 3a T4est"
order("4of Fo1r pe6ople g3ood th5e the2") // should return "Fo1r the2 g3ood 4of th5e pe6ople")

这是我目前的尝试:

function order(words) {
  let wordsArr = words.split(' ')
  let result = [];
  for (let i = 0; i < wordsArr.length; i++) {
    for (let j = 0; j < wordsArr[i].length; j++) {
      if (typeof wordsArr[i][j] === 'number') {
        result[wordsArr[i][j]] = wordsArr[i]
      }
    }
  }
  return result
}

但是这只是返回一个空数组。我的逻辑是循环遍历wordsArr 中每个单词的每个字母,一旦typeof 字母匹配'number',然后我将wordsArr[i][j]results 数组索引设置为等于wordsArr[i]。不过,这并没有按照我的预期工作,我很困惑为什么!

【问题讨论】:

  • wordsArr 是一个字符串,所以split() 的结果永远不会有number 类型的项目。
  • slappy 是对的。尝试将wordsArr[i][j] 包装在Number() 中,如果适用,这应该将单数字符串字母转换为数字
  • codewars 不会让人失望

标签: javascript arrays for-loop nested-loops


【解决方案1】:

看起来是使用sort的好案例:

function order(str){
  const r = str.split(/\s+/);
  r.sort((a,b)=>{
    let m1 = a.match(/\d+/) || [a], m2 = b.match(/\d+/) || [b];
    return m1[0]>m2[0];
  });
  return r;
}
console.log(order('is2 Thi1s T4est 3a'));
console.log(order('4of Fo1r pe6ople g3ood th5e the2'));
console.log(order('a zebra now just2 another1 test3 b'));

【讨论】:

    【解决方案2】:

    也许在一行中有其他解决方案:

    • 拆分阵列。
    • 使用sort(comparable) 对元素重新排序。
    • 将每个单词转换成数组
    • 检查是否有数字。
    • 比较sort中的这些数字
    • 加入单词(数组的元素)

      const order = str => str.split(" ").sort((a, b) => Array.from(a).find(e => 
      e.match(/\d/)) > Array.from(b).find(e => e.match(/\d/)) ? 1 : -1).join(" ")
    
      console.log(order("is2 Thi1s T4est 3a"))
      console.log(order("4of Fo1r pe6ople g3ood th5e the2"))

    【讨论】:

      【解决方案3】:

      这是一种使用简单转换的方法。

      const stripChars = word => word.replace(/[A-Za-z]+/g, '')
      
      const xf = word => parseInt(stripChars(word), 10)
      
      const order = words => words.split(' ').sort((a, b) => xf(a) - xf(b)).join(' ')
      
      console.log(
        order('is2 Thi1s T4est 3a'),
      )
      
      console.log(
        order('4of Fo1r pe6ople g3ood th5e the2'),
      )

      【讨论】:

        【解决方案4】:

        更有效的解决方案是使用正则表达式来定位每个单词中的数字字符,然后将剩余的数字转换为实际数字。

        const a = order("is2 Thi1s T4est 3a")
        const b = order("4of Fo1r pe6ople g3ood th5e the2")
        
        console.log(a, b)
        
        function order(words) {
          return words.split(' ')
            .map(w => ({word:w, n:Number(/\d+/.exec(w)[0])}))
            .sort((a, b) => a.n - b.n)
            .map(o => o.word)
        }

        它的作用是在拆分字符串后,将每个单词映射到一个包含单词及其包含的数字的对象,然后转换为实际数字。然后它根据该数字对映射数组进行排序,最后映射回只返回的单词数组。

        它假定每个单词确实都有一个数字,因此在正则表达式的.exec 上没有检查null

        【讨论】:

          【解决方案5】:

          wordsArr[i][j] 是一个字符,不管它是否是数字,所以你需要检查它是否是一个数字,你可以通过正则表达式匹配 /\d/ 来做到这一点。如果是数字,则将单词添加到结果中:

          function order(words) {
            let wordsArr = words.split(' ')
            let result = [];
            for (let i = 0; i < wordsArr.length; i++) {
              for (let j = 0; j < wordsArr[i].length; j++) {
                if (wordsArr[i][j].match(/\d/)) {
                  result[wordsArr[i][j]] = wordsArr[i]
                }
              }
            }
            return result.join(' ')
          }
          
          console.log(order("is2 Thi1s T4est 3a")) // should return "Thi1s is2 3a T4est"
          console.log(order("4of Fo1r pe6ople g3ood th5e the2")) // should return "Fo1r the2 g3ood 4of th5e pe6ople")

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-02-24
            • 1970-01-01
            • 2018-07-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多