Urgent.News

What's breaking now, across thousands of outlets.

Tech

你在错误的进行字符遍历

有问题相关代码 function pickUnicodeFor ( value ) { let unicodeSet = new Set (); let strLen = value . length ; for ( let i = 0 ; i < strLen ; i ++ ) { let word = value . charCodeAt ( i ); if ( word && ! unicodeSet . has ( word )) { word = ` \\ u ${ word . toString ( 16 ). toUpperCase ()} ` ; unicodeSet . add ( word ); } } return Array . from ( unicodeSet ); } const unicodeList = pickUnicodeFor ( " 𤋮 "…

The provided code has an issue with the way it handles Unicode characters when traversing them using the `charCodeAt` method. The problem arises because the `charCodeAt` method reads characters one byte at a time, which can lead to incorrect interpretation of multi-byte Unicode characters. This results in breaking down a three-byte character into two separate characters, leading to incorrect character representation.

When the `pickUnicodeFor` function is called with the Unicode character "𤮮", it outputs an array with the Unicode escape sequences for the two separate bytes that make up the character. The output is `["\uD850", "\uDEEE"]`, which is incorrect because the original character "𤮮" should be represented as a single Unicode escape sequence `"\u{242EE}"`.

To resolve this issue, the author suggests using the `for...of` loop instead of `charCodeAt` for character traversal. The `for...of` loop automatically iterates over characters, correctly handling multi-byte Unicode characters by treating them as a single unit rather than breaking them down into individual bytes. The code snippet provided for `pickUnicodeForOf` demonstrates the correct way to traverse Unicode characters using `for...of`.

By applying this method, the function accurately outputs the correct Unicode escape sequence for the character "𤮮" as `["\u{242EE}"]`.

In summary, the mistake in the original code lies in the improper handling of Unicode characters when using `charCodeAt`. The corrected approach is to utilize the `for...of` loop, which provides a reliable way to iterate over characters while preserving their integrity, even when dealing with multi-byte Unicode characters.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

Debounce vs Throttle: I Counted Every Call

Debounce waits for a pause; 25 fast keystrokes collapsed into exactly 1 call at 300 ms Throttle keeps a steady beat; 60 scroll events at 60 Hz became 11 calls at 100 ms Debounce alone let a slow…

  • Debounce waits for event pause before calling function
  • Throttle maintains steady pace regardless of event frequency
  • Throttle includes trailing call to ensure final event not dropped

More from Monday 12 October →