string.length
length ๋ UTF-16 ์ฝ๋ ์ ๋๊ธฐ์ค์ผ๋ก ๋ฌธ์์ด ๊ธธ์ด๋ฅผ ๋ํ๋ด๋ String object์ property์ด๋ค. string instance์ ์ฝ๊ธฐ ์ ์ฉ ๋ฐ์ดํฐ ํ๋กํผํฐ์ด๋ค.
const str = '๊ณ ์์ด ์ต๊ณ ์';
str.length; // 7Syntax
string.lengthDescription
๋ฌธ์์ด์ ์ฝ๋ ์ ๋ ์๋ฅผ ๋ฐํํ๋ค. JavaScript๋ ๋ฌธ์์ด ํฌ๋งท์ผ๋ก ์ฌ์ฉํ๋ UFT-16์ ๊ธฐ๋ณธ ๋ฌธ์๋ฅผ ํํํ๊ธฐ ์ํด 16๋นํธ๋ฅผ ์ฌ์ฉํ์ง๋ง, ์ผ๋ฐ์ ์ผ๋ก ์ฌ์ฉ๋์ง ์๋ ๋ฌธ์๋ฅผ ํํํ๊ธฐ ์ํด 2๊ฐ์ 16 ๋นํธ๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๊ฐ ์๊ธฐ ๋๋ฌธ์ ์ค์ ๋ฌธ์์ ์ผ์นํ์ง ์์ ์ ์๋ค.
ECMAScript 2016์ ์ต๋ ๊ธธ์ด๋ฅผ 2^53 - 1๋ก ์ฌ์ ์ํ์๋ค. ๊ทธ ์ด์ ์๋ ์ต๋ ๊ธธ์ด๋ ์ ํด์ ธ ์์ง ์์๋ค. Firefox์ ์๋ ๋ฌธ์์ด์ ์ต๋ ๊ธธ์ด๋ 2**30 - 2 (~1GB) ์ด๋ค. Firefox 65 ์ด์ ์ ์ต๋ ๊ธธ์ด๋ 2**28-1(~256MB) ์๋ค.
๋น ๋ฌธ์์ด์ธ ๊ฒฝ์ฐ length๋ 0dlek.
์ ์ ์์ฑ String.length๋ ๋ฌธ์์ด์ ๊ธธ์ด์ ์๊ด์ด ์์ผ๋ฉฐ String ํจ์์ arity(ํจ์๊ฐ ์ทจํ๋ ์ธ์(arguments๋๋ ํผ์ฐ์ฐ์(operand)์ ์ซ์) ์ด๋ค. 1์ ๋ฐํํ๋ค. ๐ค
Unicode
๋ฌธ์๋์ code unit์ ์ธ๊ธฐ ๋๋ฌธ์ ๋ฌธ์ ์๋ฅผ ์ป์ผ๋ ค๋ฉด ๋ค์๊ณผ ๊ฐ์ ๊ฒ์ด ํ์ํ๋ค. ๐
function getCharacterLength (str) {
// ์ฌ๊ธฐ์ ์ฌ์ฉ๋๋ ๋ฌธ์์ด ์ํ๋ ๋จ์ํ ์ฝ๋ ๋จ์๊ฐ ์๋๋ผ ๋ฌธ์ ์์์ ์ํํ๋ค.
return [...str].length; // ๐ง ๋ฐฐ์ด์ ์์๋ก ๋ง๋ ํ ๊ทธ length
}
console.log(getCharacterLength('A\uD87E\uDC04Z')) // 3
// ๊ถ์ฅํ์ง ์์ง๋ง ๋ค์๊ณผ ๊ฐ์ด ์ถ๊ฐํ ์ ์๋ค.
Object.defineProperty(String.prototype, 'charLength', {
get () {
return getCharacterLength(this);
}
});
console.log('A\uD87E\uDC04Z'.charLength); // 3Examples
length ํ ๋นํ๊ธฐ
let myString = "๊ณ ์์ด๋ ๊ท์ฝ๋ค";
// length๋ฅผ ํ ๋นํด๋ ๊ด์ฐฐ๊ฐ๋ฅํ ๊ฒฐ๊ณผ๋ ์๋ค.
myString.length = 4;
console.log(myString);
// expected output: "๊ณ ์์ด๋ ๊ท์ฝ๋ค"
console.log(myString.length);
// expected output: 8Last updated
Was this helpful?