이전 단어
문자열과 배열은 많은 유사성을 가지고 있습니다. 그들은 많은 방법을 가지고 있으며 매우 유사합니다. 그러나 그들은 차이가 있습니다. 문자열은 불변의 값이므로 읽기 전용 배열로 간주 될 수 있습니다. 이 기사는 비슷한 문자열과 배열 방법을 비교합니다
색인 가능
ecmascript5는 문자열의 특정 문자에 액세스하기 위해 사각형 괄호와 숫자 인덱스를 사용하여 문자에 액세스하는 메소드를 정의합니다.
인덱스 가능한 문자열의 가장 큰 장점은 간단하고 간단하고 charat () 호출을 사각형 괄호로 대체하는 것입니다. 뿐만 아니라 문자열이 배열처럼 행동한다는 사실은 공통 어레이 방법을 문자열에 적용 할 수있게합니다.
매개 변수가 범위를 벗어난 경우 정의되지 않은 출력
var str = "hello"; console.log (str [0]); // hconsole.log (str [[1]]); // econsole.log (str [false]); // undefinedConsole.log (str [-1]); // undefinedconsole.log (str [nan]); // undfinedconsole.log (// undfinedconsole.log
var arr = [ 'h', 'e', 'l', 'l', 'l', 'o']; console.log (arr [0]); // hconsole.log (arr [[1]]); // econsole.log (arr [false]); // un definedConsole.log (arr [-1]); // undefinedConsole.log (arr [nan]); // undefinedConsole.log (arr []); // report 오류
전환하다
split () 메소드를 사용하여 문자열을 배열로 변환 할 수 있습니다. join () 메소드를 사용하여 배열을 문자열로 변환 할 수 있습니다
【나뉘다()】
Split () 메소드는 지정된 분리기를 기반으로 문자열을 여러 문자열로 나누고 결과를 배열로 배치합니다. 분리기는 문자열 또는 정규 표현 일 수 있습니다.
이 메소드는 배열의 크기를 지정하기 위해 두 번째 매개 변수를 허용 할 수 있습니다. 두 번째 매개 변수가 0-Array.length 범위의 값인 경우 지정된 매개 변수에 따라 출력 및 다른 경우 모든 결과를 출력하십시오.
지정된 구분자가 문자열에 나타나지 않으면 원래 문자열의 값이 배열로 반환됩니다.
var colortext = '빨간색, 파란색, 녹색, 노란색'; console.log (colortext.split ( ''); // [ "r", "", "d", ","b ","l ","u ","e ","e "," ",", "g", "e", "e", "", ",", ",", " "y", "e", "l", "l", "l", "o", "w"] console.log (colortext.split ( ',')); // [ "빨간색", "파란색", "녹색", "옐로우"] 콘솔. "blue"] console.log (colortext.split ( ',', ', 6)); // [ "빨간색", "파란색", "녹색", "노란색"] console.log (colortext.split ('-')); // [ "빨간색, 파란색, 녹색"] console.log (colortext.split (//) "노란색"] console.log (colortext.split (/e/)); // [ "r", "d, blue", ", gr", "", "n, y", "llow"] console.log (colortext.split (/[^/,]+/)); // strings를 분리기 내로 변경하고 [ ",", "" "" "" "" " ie8-는 [ ",", ",", ",", ","]로 인식합니다.【가입하다()】
join () 메소드는 다른 구분기를 사용 하여이 문자열을 만들 수 있습니다. join () 메소드는 구분 기자로 사용되는 하나의 매개 변수 만 수신 한 다음 모든 배열 항목이 포함 된 문자열을 반환합니다.
join () 메소드에 값이 전달되지 않으면 쉼표를 분리기로 사용하십시오.
var a = [1,2,3]; console.log (a.join ()); // '1,2,3'console.log (a.join (' ')); //'1 2 3'Console.log (a.join ( '')); // '123'var b = new Array(10);b.join('-');//'----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------배열의 항목 값이 null 또는 정의되지 않은 경우 join () 메소드에 의해 반환 된 결과에서 값이 빈 문자열로 표시됩니다.
var colors = [1, undefined, 2, null, 3]; console.log (colors.join ()); // '1 ,, 2 ,, 3'
문자열은 배열 객체이므로 join () 메소드를 사용할 수도 있습니다.
console.log (array.prototype.join.call ( 'hello', '-')); // "hello"
var str = 'test'; var arr = str.split ( '') // [ "t", "e", "s", "t"] console.log (arr.join ( '-')); // 'tes-t'
스 플라이 싱
문자열 및 배열은 스 플라이 싱 메소드를 공유합니다 ()
var value = 'hello'; console.log (value.concat ( 'world')); // 'helloworld'console.log (value.concat (['world ']))); //'helloworld'console.log (value.concat ([ 'world']]); // 'helloworld'
var value = [ 'hello']; console.log (value.concat ( 'world')); // [ "hello", "world"] console.log (value.concat ([ 'world'])); // [ "hello", "world"] console.log (value.concat ([ 'world']]); // [ "hello", [ "World"] Console.log (Value.concat ([[ 'World']])); // [ "Hello", [ "World"]]]]
만들다
문자열과 배열 모두 생성 메소드 Slice ()가 있으며, 이는 각각 하위 문자 및 서브 배달을 생성하는 데 사용됩니다.
Slice () 메소드는 현재 배열 (또는 문자열)의 하나 이상의 항목을 기반으로 새 배열 (또는 문자열)을 생성하고, 하나 또는 두 개의 매개 변수, 즉 항목의 시작 및 종료 위치를 반환하고 마지막으로 새 배열 (또는 문자열)을 반환합니다.
슬라이스 (start, end) 메소드에는 두 개의 매개 변수 시작 및 종료가 필요합니다.이 매개 변수는 시작 위치 에서이 배열 (또는 문자열)에서 끝 위치 (또는 포함되지 않음)로 서브 어레이 (또는 문자열)를 반환해야합니다. 끝이 정의되지 않았거나 존재하지 않으면 모든 항목을 시작 위치에서 배열 끝 (또는 문자열)으로 반환합니다.
시작이 음수 인 경우 start = max (length + start, 0)
끝이 음수 인 경우 end = max (length + end, 0)
시작과 끝은 위치를 바꿀 수 없습니다
var 번호 = [1,2,3,4,5]; Console.log (Numbers.Slice (2)); // [3,4,5] Console.log (Numbers.Slice (2, undefined)); // [3,4,5] Consol e.log (numbers.slice (2,3)); // [3] console.log (numbers.slice (2,1)); // [] console.log (numbers.slice (-3)); // 3+5 = 2 -> [3,4,5] console.log (numbers.slice (-8)); // max (5 + -8,0) = 0-> [1,2,3,4,5] console.log (numbers.slice (0, -3)); // -3 + 5 = 2-> [1,2] console.log (numbers.slice (-2, -1)); // -2+5 = 3; -1+5 = 4; -> [4]
var stringValue = 'Hello World'; console.log (stringValue.slice ()); // 'Hello World'Console.log (stringValue.slice (2)); //'llo world'console.log (StringValue.slice (20)); // 'console.log (2, undrefed); World'Console.log (StringValue.slice (2, -5)); // 'llo'console.log (stringvalue.slice (2, -20)); // ''console.log (stringvalue.slice (-2,2)); // 'console.log (-2, //'); console.log (StringValue.slice (-2,20)); // 'ld'console.log (stringValue.slice (-20,2)); //'He'console.log (StringValue.slice (-20, -2)); 'Hello Wor'
위치
문자열과 배열 모두 위치를 찾는 두 가지 방법이 있습니다 : indexof ()와 lastIndexof (). 위치 방법은 괄호 [] 읽기 방법과 정확히 반대입니다. 하나는 항목을 통해 인덱스를 찾는 것이고 다른 하나는 인덱스를 통해 항목을 찾는 것입니다.
【indexof () of
indexof (검색, 시작) 메소드는 두 개의 매개 변수 검색 및 시작을 수신하여 검색이 처음 나타나는 위치를 반환하고, 찾을 수없는 경우 -1을 반환합니다.
문자열의 검색 매개 변수는 String () 변환 함수를 호출하여 매개 변수의 비 스트링 값을 문자열로 변환합니다. 배열의 검색 매개 변수는 엄격한 평등 연산자 (===)를 사용하여 비교됩니다.
배열이든 문자열이든, 두 번째 매개 변수 시작은 숫자 () 변환 함수를 암시 적으로 호출하여 숫자가 아닌 값을 숫자 값으로 변환합니다. 이 매개 변수가 무시되거나 매개 변수가 정의되지 않았거나 nan이면 start = 0
시작 매개 변수가 음수 인 경우 문자열의 처리는 시작 = 0입니다. 배열의 처리는 시작 = max (0, start+length)입니다.
var string = 'Hello World World '; console.log (String.indexof ('ld ')); // 9console.log (String.indexof ('ld ', undefined)); // 9console.log (String.indexof ('ld ', nan)); // 9console.log ('ld ', -1); // 9console.log ('ld ', -1); ring.indexof ( 'ld', -1)); // 9console.log (String.indexof ( 'ld', -1)); // 9console.log (String.indexof (string.indexof) 'ld', -1)); // 9console.log (String.indexof ( 'ld', -1)); // 9console.log (String.indexof ( 'ld', -1)); // 9 console.log (string.indexof ( 'ld', 10)); // 15console.log (String.indexof ( 'ld', [10])); // 15console.log (String.index ( 'true', [10]); // -1console.log (String.indexof (false, [10]); // -1console.log (String.indexof (false, [10]); // -1var arr = [ 'a', 'b', 'c', 'd', 'e', 'a', 'b']; console.log (arr.indexof ( 'a', undefined)); // 0console.log (arr.indexof ( 'a', nan)); // 0consol e.log (arr.indexof ( 'a', 1)); // 5console.log (arr.indexof ( 'a', true)); // 5console.log (arr.indexof ( 'a', -1)); // max (0, -1+7) = 6; -1console.log (arr.indexof ( 'a', -5)); // max (0, -5+7) = 2; 5console.log (arr.indexof ( 'a', -50)); // max (0, -50+7) = 0; 0
【LastIndexof ()】
indexof () 메소드와 달리 LastIndexof () 메소드는 오른쪽에서 왼쪽으로 바라 보는 것입니다.
LastIndexof (Search, Start) 메소드는 두 개의 매개 변수 검색 및 시작을 수신하여 SearchString이 처음 나타나는 위치를 반환하고, 찾을 수없는 경우 -1을 반환합니다.
마찬가지로 문자열의 검색 매개 변수는 String () 변환 함수를 호출하여 매개 변수의 비 스트링 값을 문자열로 변환합니다. 배열의 검색 매개 변수는 엄격한 평등 연산자 (===)를 사용하여 비교됩니다.
배열이든 문자열이든, 두 번째 매개 변수 시작은 숫자 () 변환 함수를 암시 적으로 호출하여 비수막 값 (정의되지 않은 제외)을 숫자 값으로 변환합니다.
이 매개 변수가 무시되거나 매개 변수가 정의되지 않았거나 nan이면 문자열의 처리는 시작 = 길이 -1; 배열의 처리가 시작되는 동안 = 0
시작 매개 변수가 음수 인 경우 문자열의 처리는 시작 = 0입니다. 배열의 처리는 시작 = max (0, start+length)입니다.
var string = 'Hello World World '; console.log (String.lastIndexof ('ld ')); // 15console.log (String.lastIndexof ('ld ', undefined)); // 15console.log (strin g.lastindexof ( 'ld', nan)); // 15console.log (string.lastindexof ( 'ld', -1)); // -1console.log (String.lastIndexof ( 'h', -1)); // 0c OnSole.log (String.lastIndexof ( 'w', undefined)); // 12console.log (String.lastIndexof ( 'ld', 10)); // 9console.log (String.last indexof ( 'ld', [10]); // 9console.log (String.lastIndexof ( 'ld', [10]); // -1console.log (String.lastIndexof (false, [10]); // -1var arr = [1,2,3, '1', '2', '3']; console.log (arr.lastindexof ( '2')); // 4console.log (Ar [ 'a', 'b', 'c', 'c', 'd', 'e', 'a', 'b']; console.log (arr.lastindexof ( 'b')); // 6console.log (arr.lastindexof ( 'b', undrefined)); // -1console.log ( 'a', u ndefined); // 0console.log (arr.lastindexof ( 'b', nan)); // -1console.log (arr.lastindexof ( 'b', 1)); // 1console.log (arr.lastindexof ( 'b', -1)); // max (0, -1+7) = 6; 6console.log (arr.lastindexof ( 'b', -5)); // max (0, -5+7) = 2; 1console.log (arr.lastindexof ( 'b', -50)); // max (0, -50+7) = 0; -1
JavaScript에서 배열 및 문자열 메소드의 위의 비교는 내가 공유하는 모든 내용입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.