Javascript-배열의 각 문자열에 트림 기능 적용
배열의 각 문자열을 자르고 싶습니다.
x = [' aa ', ' bb '];
산출
['aa', 'bb']
내 첫 번째 재판은
x.map(String.prototype.trim.apply)
Chromium에서 "TypeError : Function.prototype.apply가 정의되지 않은 상태에서 호출되었습니다. 이것은 정의되지 않았으며 함수가 아닙니다."
그런 다음 시도했습니다
x.map(function(s) { return String.prototype.trim.apply(s); });
효과가있다. 차이점이 뭐야?
String.prototype.trim.apply은 IS Function.prototype.apply방식 에 구애 됨이없이 trim. map문자열, 인덱스 및 배열을 인수로 사용하여 호출 undefined하고 thisArg에 대해서는 아무 것도 ( ) 호출하지 않습니다. 그러나 apply함수에서 호출 될 것으로 예상합니다.
var apply = String.prototype.trim.apply;
apply.call(undefined, x[0], 0, x) // TypeError
할 수있는 일은 trim함수를 컨텍스트로 전달하는 것입니다 call.
[' aa ', ' bb '].map(Function.prototype.call, String.prototype.trim)
// ['aa', 'bb']
여기서 일어나는 일은
var call = Function.prototype.call,
trim = String.prototype.trim;
call.call(trim, x[0], 0, x) ≡
trim.call(x[0], 0, x) ≡
x[0].trim(0, x); // the arguments don't matter to trim
또는 화살표 함수로 해결할 수 있습니다.
x.map(s => s.trim());
JQuery를 사용하는 경우 IE8에서도 작동하므로이 작업을 수행하는 더 좋은 방법은 다음과 같습니다 (IE8을 지원해야 함).
$.map([' aa ', ' bb ', ' cc '], $.trim);
종속성이없는 간단한 변형 :
for (var i = 0; i < array.length; i++) {
array[i] = array[i].trim()
}
ES6 변형 :
const newArray = oldArray.map(string => string.trim())
ES6 기능 변형 :
const trimArray = array => array.map(string => string.trim())
먼저 간단하게하십시오.
x.map(function(s) { return s.trim() });
그런 다음 첫 번째 것이 작동하지 않는 이유는 문자열이 컨텍스트가 아닌 콜백에 대한 인수로 전달되기 때문입니다. 에 인수를 전달하지 않으면 apply다음과 같은 메시지가 표시됩니다.
var f = String.prototype.trim.apply; f.call();
이제 대부분 재미로 map콜백을 이런 방식으로 사용하는 것이 만족스럽지 않고 인수가 아닌 컨텍스트를 사용하여 함수를 전달할 수 있기를 원한다고 가정 해 보겠습니다 .
그런 다음 이렇게 할 수 있습니다.
Object.defineProperty(Array.prototype, "maprec", {
value: function(cb){
return this.map(function(v){ return cb.call(v) })
}
});
console.log([' aa ', ' bb '].maprec(String.prototype.trim)); // logs ["aa", "bb"]
소유하지 않은 객체 (여기서는 배열의 프로토 타입)를 수정하는 것은 나쁜 습관으로 널리 인식되기 때문에 "대부분 재미로"라고 말했습니다. 그러나 배열과 콜백을 인수로 사용하는 실용적인 함수를 만들 수도 있습니다.
가장 짧고 빠른 방법을 얻기 위해 문자열 배열을 트리밍하는 몇 가지 방법을 비교했습니다. 관심있는 사람은 jsperf에 대한 성능 테스트입니다. http://jsperf.com/trim-array-of-strings
var chunks = " .root , .parent > .child ".split(',')
var trimmed1 = chunks.map(Function.prototype.call, String.prototype.trim);
var trimmed2 = chunks.map(function (str) { return str.trim(); });
var trimmed3 = chunks.map(str => str.trim());
var trimmed4 = $.map(chunks, $.trim);
참고 : jQuery는 입력 할 문자 수를 비교하기 위해 여기에 있습니다.)
Bergi의 완벽한 대답에 영향을 미침에 따라 추가하고 싶습니다. this논쟁 을하지 않는 방법에 대해 다음과 같이 동일한 작업을 수행 할 수 있습니다.
var x = [' aa ', ' bb '],
y = x.map(Function.prototype.call.bind(String.prototype.trim))
간단하고 어리석게 유지하십시오.
암호
[' aa ', ' b b ', ' c c '].map(i=>i.trim());
산출
["aa", "b b", "c c"]
var x = [" aa ", " bb "];
console.log(x); // => [" aa ", " bb "]
// remove whitespaces from both sides of each value in the array
x.forEach(function(value, index){
x[index] = value.trim();
});
console.log(x); // => ["aa", "bb"]
All major browsers support forEach(), but note that IE supports it only beginning from version 9.
Another ES6 alternative
const row_arr = ['a ', ' b' , ' c ', 'd'];
const trimed_arr = row_arr.map(str => str.trim());
console.log(trimed_arr); // <== ['a', 'b', 'c', 'd']
### Code
<!-- language: lang-js -->
var x= [' aa ', ' b b ', ' c c ']
var x = x.split(",");
x = x.map(function (el) {
return el.trim();
console.log(x)
### Output
<!-- language: lang-none -->
["aa", "b b", "c c"]
'program story' 카테고리의 다른 글
| Python에서 소수의 효율적인 무한 생성기를 구현하는 방법은 무엇입니까? (0) | 2020.12.06 |
|---|---|
| Node.js : 각… 작동하지 않음 (0) | 2020.12.06 |
| dyld`__abort_with_payload : 오류 메시지 없음 (0) | 2020.12.06 |
| BOOL에서 NSString으로 (0) | 2020.12.06 |
| 백그라운드 / 분리 된 SSH 세션을 어떻게 종료합니까? (0) | 2020.12.06 |