[英]Access multiple characters using bracket notation?
I'm returning the 2nd, 3rd and 5th numbers in the string '123456'
by using 我通过使用以下命令返回字符串'123456'
的第二,第三和第五个数字
function returnSome(numbers) {
return numbers[1] + numbers[2] + numbers[4]
}
returnSome('123456'); //2, 3, 5
Simple enough right? 很简单吧? What I'm wondering is whether there is a shorter way to write that out? 我想知道的是,是否存在一种更短的书写方式? something like numbers[1][2][4]? 像数字[1] [2] [4]之类的东西?
I can't seem to find an answer online! 我似乎无法在网上找到答案! (It may well be that I just don't know the correct terminology!) (很可能是我不知道正确的术语!)
Not really shorter, but you could use an array of indices and map that to the strings characters, then join them to a new string: 并不是很短,但是您可以使用索引数组并将其映射到字符串字符,然后将它们连接到新字符串:
[1, 2, 4].map(i => numbers[i]).join("")
something like numbers[1][2][4]? 像数字[1] [2] [4]之类的东西?
We can get quite close with currying: 我们可以通过currying来获得非常接近的结果:
const wrap = (str, res = "") => index => index + 1 ? wrap(str, res + str[index]) : res;
wrap(numbers)(1)(2)(4)()
You can turn the indices you want into a string that you iterate over and pull out from the array you pass in. 您可以将所需的索引转换为迭代的字符串,并从传入的数组中拉出。
let returnSome = (numbers, sections) => sections.split("").map(i => +numbers[i]);
let returnSome = (numbers, sections) => sections.split("").map(i => +numbers[i]); console.log( returnSome('123456', '124') ); //2, 3, 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.