gpt4 book ai didi

javascript - 替代javascript中的charAt方法

转载 作者:行者123 更新时间:2023-12-01 09:12:09 26 4
gpt4 key购买 nike

这是手头的任务:

Write a function called charAt which accepts a string and an index (number) and returns the character at that index.

The function should return an empty string if the number is greater than the length of the string.

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

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

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

最佳答案

它看起来大部分都很好,除了一个问题 - 有许多奇怪的字符(由代理对组成的字符,有时也称为多字节字符)在一个索引中占用了多个索引字符串。一个例子是💖。如果字符串中包含这样一个字符,它将被视为字符串中的两个个指标:

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")
);

如果这对您的情况来说可能是个问题,请考虑先使用 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),
);

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

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));

关于javascript - 替代javascript中的charAt方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59508222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com