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