1

我正在尝试编写一个接收数组和字符串的函数。该函数需要使用数组方法 .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")
4

2 回答 2

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")
''
>
于 2018-06-06T14:08:29.817 回答
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"));

于 2018-06-06T14:10:16.283 回答