문자열이 있으면
const string = 'This is a value and this is a field'
문자열을 분할 한 후 용어 value
와 용어를 어떻게 해체 할 수 field
있습니까?
같은 것,
const [theValue, theField] = string.split(" ")[3][8]
가능합니까?
Destructuring을 사용하려는 경우 가능하지만 권장하지 않습니다 . 정말 혼란스러워 보입니다 .
const string = 'This is a value and this is a field'
const [,,,theValue,,,,, theField] = string.split(" ");
console.log(theValue, theField);
iterables를 분해 할 때 값을 나열하는 것은 선택 사항 이기 때문에 가능합니다 . 마찬가지로 다음을 수행 할 수 있습니다.
const [, one] = [0, 1]
1
라는 변수 에 넣 습니다 one
.
De-sugared, 첫 번째 코드는 다음과 같습니다.
const string = 'This is a value and this is a field'
const splits = string.split(" ");
const [
firstWord,
secondWord,
thirdWord,
theValue,
fifthWord,
sixthWord,
seventhWord,
eighthWord,
theField
] = string.split(" ");
console.log(theValue, theField);
( 첫 번째 코드에서 선언되지 않은 변수를 제외 theValue
하고 theField
)
공백이 아닌 문자를 일치시킨 다음 결과 배열의 3 번째 및 8 번째 인덱스를 추출하는 것이 더 합리적입니다.
const string = 'This is a value and this is a field';
const words = string.match(/\S+/g);
const theValue = words[3];
const theField = words[8];
console.log(theValue, theField);
(공백 \S+
을 분할하는 대신 공백이 아닌 문자를 일치시키는 것은 더 신뢰할 수있는 결과를 .split
얻을 수 있습니다. 사용 하면 선행 또는 후행 공백이있을 때 빈 문자열이 선행 또는 후행 될 수 있습니다.)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다