【问题标题】:Javascript: Get nth character of string (JSChallenger)Javascript:获取字符串的第 n 个字符(JSChallenger)
【发布时间】:2022-06-13 17:00:30
【问题描述】:

我是个新手,目前正在学习 Javacript。 我在 JSChallenger 上遇到了这个问题,并且一直在努力解决这个问题。 这是我的代码:

// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a, n)
{let string = a;
let index = n;
return string.charAt(index);
}

谁能指出我的错误? 非常感谢!

【问题讨论】:

  • 它工作正常。我在这段代码中没有看到任何错误。请参考这个小提琴jsfiddle.net/02gs5dby
  • 似乎工作得很好。有什么问题? (顺便说一句,您可以跳过创建两个额外的变量,只需 return a[n]
  • 它工作正常但是你调用了这个函数吗?在你的函数 myFunction(string, number); 下方添加这个并更改参数以适合您的情况。
  • “谁能指出我的错误?” 什么错误?是什么告诉你有什么问题?网站?如果是这样,它可能是在抱怨stringindex——它们完全没有必要。或者,它可能抱怨未处理字符串中的多代码单元代码点(我的博客文章详细信息here),但这不太可能。 (如果这是问题所在,解决方案将是 for (const ch of a) { if (n-- === 0) { return ch; } }return [...a][n];)。
  • 一切正常。请注意,数组索引从 0 开始。所以 n=0 将返回第一个字符。

标签: javascript


【解决方案1】:

试试这个

function myFunction(a, n){
return a[n - 1];}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:
// there is a shorter way to do this since you want to find what's missing here is what's missing. 
function myFunction(a, n){
    let string = a;
    let index = n-1;
    return string.charAt(index);
}

【讨论】:

    【解决方案3】:

    JS 字符串的索引从 0 开始枚举,所以 n 应该减 1

    // Write a function that takes a string (a) and a number (n) as argument
    // Return the nth character of 'a'
    function myFunction(a, n)
    {let string = a;
    let index = n;
    return string.charAt(index-1);
    }
    

    最简单的写法是:

    // Write a function that takes a string (a) and a number (n) as argument
    // Return the nth character of 'a'
    
    function myFunction(a,n) {
    
           return a[n - 1];
      }
    

    意思是从 myFunction 的字符串 "a" 返回索引 "[n-1]" , "n-1" 这是获取正确索引所需的操作,因为字符串索引从 0 开始枚举。

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 2017-09-24
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多