如何在特定索引处返回字符?

时间:2018-06-06 13:54:16

标签: javascript arrays

我正在尝试编写一个接受数组和字符串的函数。该函数需要使用数组方法.indexOf并找到数组中传入字符串的索引。然后它需要使用方法.charAt来查找字符串中该索引处的字符并返回该字符。我很困惑,不确定我需要做什么。非常感谢任何帮助!

以下是我的尝试:

cipherize = (arr, str) => {
  let index = arr.indexOf(str)
  return str.charAt(0)
}

必须通过这些测试:

should return "l" when called as cipherize(["books", "computers", "paper", "tablets"], "tablets")
should return "" when called as cipherize(["blue", "green", "yellow", "purple", "red"], "red")

2 个答案:

答案 0 :(得分:2)

@Stoney ,只需将0替换为index即可。

> const cipherize = (arr, str) => {
...   let index = arr.indexOf(str)
...   return str.charAt(index)
... }
undefined
> cipherize(["books", "computers", "paper", "tablets"], "tablets");
'l'
>
> cipherize(["blue", "green", "yellow", "purple", "red"], "red")
''
>

答案 1 :(得分:1)

只需将传递的字符串的index传递给charAt()

cipherize = (arr, str) => {
  let index = arr.indexOf(str)
  return str.charAt(index); //pass index here
}
console.log(cipherize(["books", "computers", "paper", "tablets"], "tablets"));

console.log(cipherize(["blue", "green", "yellow", "purple", "red"], "red"));