programing

string.charAt(x) 또는 string[x]?

yoursource 2022. 9. 17. 22:27
반응형

string.charAt(x) 또는 string[x]?

제가 사용해야 할 이유가 있나요?string.charAt(x) 표기법 string[x]

IE7 이하를 제외한 모든 주요 브라우저에서 괄호 표기가 작동합니다.

// Bracket Notation
"Test String1"[6]

// charAt Implementation
"Test String1".charAt(6)

이전에는 다음과 같은 이유로 대괄호를 사용하는 것은 좋지 않았습니다(출처).

이 표기법은 IE7에서는 동작하지 않습니다.첫 번째 코드 스니펫은 IE7에서 정의되지 않은 상태로 반환됩니다.코드 전체에 걸쳐 문자열에 대괄호 표기를 사용하고 있는 경우로 이행하고 싶은 경우.charAt(pos)코드 전체에 괄호가 사용되고 있기 때문에 문자열인지 어레이/개체인지를 쉽게 검출할 수 없습니다.

이 표기법을 사용하여 문자를 설정할 수 없습니다.어떤 경고도 없기 때문에 매우 혼란스럽고 답답합니다.를 사용하고 있는 경우.charAt(pos)함수에 대한 유혹은 없었을 겁니다.

MDN에서:

문자열 내의 개별 문자에 액세스하는 방법은 두 가지가 있습니다.첫 번째는 ECMAScript 3의 일부인 방법입니다.

return 'cat'.charAt(1); // returns "a"

다른 방법은 문자열을 배열과 같은 개체로 처리하는 것입니다. 여기서 각 문자는 숫자 인덱스에 해당합니다.이것은 IE를 제외한 대부분의 브라우저에서 첫 번째 버전부터 지원되고 있습니다.ECMAScript 5:

return 'cat'[1]; // returns "a"

두 번째 방법에서는 ECMAScript 5 지원이 필요합니다(일부 오래된 브라우저에서는 지원되지 않습니다).

두 경우 모두 문자열은 불변하기 때문에 개별 문자를 변경하려고 해도 효과가 없습니다. 즉, 문자열의 속성은 "쓰기 가능"하지도 않고 "설정 가능"하지도 않습니다.

  • str.charAt(i)IE6/IE7과의 호환성이 필요한 경우는, 호환성의 관점에서 보면, 를 추천합니다.
  • str[i]++8 IE8 + 모모모 ( /// / Firefox / Chrome 、 Safari 2 + )iOS / Android에서 작동합니다.

엣지 케이스에서는 다른 결과를 얻을 수 있습니다.

'hello'[NaN] // undefined
'hello'.charAt(NaN) // 'h'

'hello'[true] //undefined
'hello'.charAt(true) // 'e'

charAt 함수는 인덱스가 사양의 숫자로 변환되는 방법에 따라 달라집니다.

범위를 벗어나거나 정수가 아닌 인덱스에 액세스하려고 하면 차이가 있습니다.

string[x] 있는 문자를 반환합니다.x'1'의 th stringx0 ~ 0 의 입니다.string.length-1및 를 반환한다.undefined렇지지그

string.charAt(x)x여기서 설명하는 프로세스를 사용하여 정수로 변환합니다(기본적으로 반올림).x된 경우x이며, 0이 을 반환합니다.parseInt(x)NaN) ) 、 ~ 「 0 」0, 그합니다.string.length-1이치노

다음은 몇 가지 예입니다.

"Hello"[313]    //undefined
"Hello".charAt(313)    //"", 313 is out of bounds

"Hello"[3.14]    //undefined
"Hello".charAt(3.14)    //'l', rounds 3.14 down to 3

"Hello"[true]    //undefined
"Hello".charAt(true)    //'e', converts true to the integer 1

"Hello"["World"]    //undefined
"Hello".charAt("World")    //'H', "World" evaluates to NaN, which gets converted to 0

"Hello"[Infinity]    //undefined
"Hello".charAt(Infinity)    //"", Infinity is out of bounds

다른 으로는 '하다'에 하는 것입니다.string[x]는 아무것도 않고스러울 수 ), 은 (혼란스러울 수 있습니다), 할당은 (알려할 수 있습니다).string.charAt(x)에러입니다(예상대로).

var str = "Hello";
str[0] = 'Y';
console.log(str);    //Still "Hello", the above assignment did nothing
str.charAt(0) = 'Y';    //Error, invalid left-hand side in assignment

string[x]동작하지 않는 은 Javascript 문자열이 불변하기 때문입니다.

String.charAt()는 원래 표준으로 모든 브라우저에서 작동합니다.IE 8+ 및 기타 브라우저에서는 괄호 표기법을 사용하여 문자에 액세스할 수 있지만 IE 7 이하에서는 지원되지 않습니다.

하고 싶은 경우는 IE 7 을 사용하여 str.split('')모든 브라우저와 호환되는 어레이로 사용할 수 있습니다.

var testString = "Hello"; 
var charArr = testString.split("");
charArr[1]; // "e"

대 스트링인덱스액세스의 롭습니다.charAt()★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.charAtdiscloss.more.discloss.

CharAt와 인덱스 1

ChartAt와 인덱스2

차트 At와 인덱스 3

를 사용하는 것의 차이점은 무엇입니까?charAt(index) ★★★★★★★★★★★★★★★★★」string[index]세스스 할?? ???

# 지수값 charAt(반환값) 괄호 표기법(반환값)
1 인덱스 > = 길이 '' undefined
2 인덱스 < 0 '' undefined
3 인덱스: false(가짜) 0 문자 undefined
4 인덱스 = true 1 문자 undefined
5 Number(인덱스: 문자열) === NaN 0 문자 undefined
6 번호(색인: 문자열) !== NaN 색인 문자 색인 문자
7 인덱스: 10진수 character at at at의 Math.floor(Number(index)) undefined

주의:

  • 의 경우,index인덱스를 검색하기 전에 먼저 숫자를 입력하도록 시도됩니다.

    • 이치노 Number(true)과 1로 합니다.Number(false) 0.10으로 평가됩니다.
    • 모든 거짓 값은 인덱스 0을 반환합니다.
    • 단일 요소 [1] 또는 ['1']을(를) 포함하는 배열은 강제 적용 시 숫자를 반환합니다.하는 배열은 " "를 반환합니다.NaN위의 표에 따라 치료가 이루어집니다.
    • 숫자,합니다.「 10 」 、 「 1 」Math.floor(Number(index))용됩니니다다
  • 괄호 표기법에서는 인덱스가 하나의 요소를 포함하는 문자열 또는 배열일 때 유형 강제가 시행됩니다.

    • 부울 값은 강제로 입력되지 않습니다. ★★★★★★★★★★★★★★★★★.true하지 않다1true ★★★★★★★★★★★★★★★★★」false 다 '''를 반환한다.undefined.
    • 한 모든 값, 0을 반환한다.undefined.
    • 은 10을 반환한다.undefined.
  • type falsy = null | undefined | NaN | ''

    • falsy하지 않습니다.
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

/** index > str.length */
console.log({ charAt: str.charAt(27) }); // returns ''
console.log({ brackets: str[27] }); // returns undefined

/** index < 0 */
console.log({ charAt: str.charAt(-2) }); // returns ''
console.log({ brackets: str[-2] }); // returns undefined

/** Falsy Values */

// All falsy values, return character at index 0
console.log({ charAt: str.charAt(NaN) }); // returns 'A'
console.log({ charAt: str.charAt(false) }); // returns 'A'
console.log({ charAt: str.charAt(undefined) }); // returns 'A'
console.log({ charAt: str.charAt(null) }); // returns 'A'
console.log({ charAt: str.charAt('') }); // returns 'A'

// All falsy values except 0, return undefined
console.log({ brackets: str[NaN] }); // returns undefined
console.log({ brackets: str[false] }); // returns undefined
console.log({ brackets: str[undefined] }); // returns undefined
console.log({ brackets: str[null] }); // returns undefined
console.log({ brackets: str[''] }); // returns undefined

/** index = Boolean(true) */
console.log({ charAt: str.charAt(true) }); // returns 'B', (character at index 1)
console.log({ brackets: str[true] }); // undefined

/** Type coercion: Failure */
console.log({ charAt: str.charAt('A1') }); // returns 'A' (character at index 0)
console.log({ brackets: str['ABC'] }); // returns undefined

/** Type coercion: Success */
console.log({ charAt: str.charAt('1') }); // returns 'B' (attempts to access index after type coercion)
console.log({ brackets: str['1'] }); // returns undefined (attempts to access index after type coercion)

/** Decimal Values */
console.log({ charAt: str.charAt(1.9) }); // returns 'B', applies Math.floor(Number(index))
console.log({ charAt: str.charAt('1.9') }); // returns 'B', applies Math.floor(Number(index))
console.log({ charAt: str.charAt(['1.9']) }); // returns 'B', applies Math.floor(Number(index))

console.log({ brackets: str[1.9] }); // returns undefined

Github에 대한 빠른 참조 보기

언급URL : https://stackoverflow.com/questions/5943726/string-charatx-or-stringx

반응형