javascript中charAt方法的替代方法

Gol*_*nda 3 javascript

这是手头的任务:

编写一个名为 charAt 的函数,它接受一个字符串和一个索引(数字)并返回该索引处的字符。

如果数字大于字符串的长度,该函数应返回一个空字符串。

关键是你不能使用内置的 charAt 方法。

除了不包含 if 语句之外,我是否在做正确的事情?另外,正确的实现是什么样的?(JS新手,所以我提前道歉)。

function charAt(string, index) {
  var charAt = string[index];
  return charAt;
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 8

它看起来基本没问题,除了一个问题 - 有许多奇数字符(由代理对组成的字符,有时也称为多字节字符)在字符串中占用了多个索引。一个例子是。如果字符串包含这样的字符,它将被视为字符串中的两个索引:

function charAt(string, index) {
  var charAt = string[index];
  return charAt;
}
console.log(
  charAt('foobar', 3), // Broken character, wrong
  charAt('foobar', 4), // Broken character, wrong
  charAt('foobar', 5), // Wrong character (should be "a", not "b")
  charAt('foobar', 6), // Wrong character (should be "r", not "a")
);
Run Code Online (Sandbox Code Playgroud)

如果这对您的情况来说可能存在问题,请考虑Array.from先将其转换为数组:

function charAt(string, index) {
  var charAt = Array.from(string)[index];
  return charAt;
}
console.log(
  charAt('foobar', 3),
  charAt('foobar', 4),
  charAt('foobar', 5),
  charAt('foobar', 6),
);
Run Code Online (Sandbox Code Playgroud)

或者,当索引不存在时返回空字符串:

function charAt(string, index) {
  return Array.from(string)[index] || '';
}
console.log(
  charAt('foobar', 3),
  charAt('foobar', 4),
  charAt('foobar', 5),
  charAt('foobar', 6),
);
console.log(charAt('foobar', 123));
Run Code Online (Sandbox Code Playgroud)