简体   繁体   English

javascript中charAt方法的替代方法

[英]Alternative to charAt method in javascript

Here is the task at hand:这是手头的任务:

Write a function called charAt which accepts a string and an index (number) and returns the character at that index.编写一个名为 charAt 的函数,它接受一个字符串和一个索引(数字)并返回该索引处的字符。

The function should return an empty string if the number is greater than the length of the string.如果数字大于字符串的长度,该函数应返回一个空字符串。

The kicker is that you CAN NOT use the built in charAt method.关键是你不能使用内置的 charAt 方法。

Am I doing what it is asking correctly aside from not including the if statement?除了不包含 if 语句之外,我是否在做正确的事情? Also, what would a correct implementation of that look like?另外,正确的实现是什么样的? (New to JS so my apologies in advance). (JS新手,所以我提前道歉)。

function charAt(string, index) {
  var charAt = string[index];
  return charAt;
}

It looks mostly fine, except for one issue - there are a number of odd characters (those composed of surrogate pairs, also sometimes called multibyte characters) which take up more than a single index in a string.它看起来基本没问题,除了一个问题 - 有许多奇数字符(由代理对组成的字符,有时也称为多字节字符)在字符串中占用了多个索引。 An example is 💖.一个例子是💖。 If the string contains a character like this, it will be counted as two indicies in the string:如果字符串包含这样的字符,它将被视为字符串中的两个索引:

 function charAt(string, index) { var charAt = string[index]; return charAt; } console.log( charAt('foo💖bar', 3), // Broken character, wrong charAt('foo💖bar', 4), // Broken character, wrong charAt('foo💖bar', 5), // Wrong character (should be "a", not "b") charAt('foo💖bar', 6), // Wrong character (should be "r", not "a") );

If this is a possible problem for your situation, consider using Array.from to turn it into an array first:如果这对您的情况来说可能存在问题,请考虑先使用Array.from将其转换为数组:

 function charAt(string, index) { var charAt = Array.from(string)[index]; return charAt; } console.log( charAt('foo💖bar', 3), charAt('foo💖bar', 4), charAt('foo💖bar', 5), charAt('foo💖bar', 6), );

Or, with the empty string being returned when the index doesn't exist:或者,当索引不存在时返回空字符串:

 function charAt(string, index) { return Array.from(string)[index] || ''; } console.log( charAt('foo💖bar', 3), charAt('foo💖bar', 4), charAt('foo💖bar', 5), charAt('foo💖bar', 6), ); console.log(charAt('foo💖bar', 123));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM