簡體   English   中英

JavaScript - 接受字符串和索引(數字)並返回該索引處的字符的函數

[英]JavaScript - function which accepts a string and an index (number) and returns the character at that index

我想編寫一個名為charAt的函數,它接受一個字符串和一個索引(數字)並返回該索引處的字符。

如果數字大於字符串的長度,該函數應返回一個空字符串。

不要使用內置的 charAt 方法 - 如果這樣做,測試將失敗!

function charAt(str, num){
  return str.indexOf(num);
}


charAt('awesome', 2);

我知道我的代碼正在檢查數字 2 是否包含在字符串 'awesome' 中並正確返回 -1,這告訴我數字 2 不包含在該字符串中。

如何編寫代碼以返回從索引 2 開始的字母?

function charAt(str, num) {
    return str[num] ? str[num] : '';
}

對於這個綜合問題,像這樣的東西是一個相對優雅的解決方案。

基本和簡單的解決方案。

 function charAt(str, num) { return str.slice(num, num + 1) || ""; } console.log(charAt("awesome", 10)); // OR const charAt2 = (str, num) => str.slice(num, num + 1) || ""; console.log(charAt2("awesome", 2)); //OR add in prototype String.prototype.safeCharAt = function safeCharAt(num) { return this.slice(num, num + 1) || ""; }; console.log("awesome".safeCharAt(2)); console.log("awesome".safeCharAt(10));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM