숫자 문자열을 숫자 배열로 변환하는 방법은 무엇입니까?
문자열 아래에 있습니다-
var a = "1,2,3,4";
내가 할 때-
var b = a.split(',');
내가 얻을 b
로["1", "2", "3", "4"]
내가 얻을 수있는 뭔가 할 수있는 b
로를 [1, 2, 3, 4]
?
Array.map
각 요소를 숫자로 변환 하는 데 사용할 수 있습니다 .
var a = "1,2,3,4";
var b = a.split(',').map(function(item) {
return parseInt(item, 10);
});
문서 확인
또는 사용자가 지적한대로보다 우아하게 : thg435
var b = a.split(',').map(Number);
Number()
나머지는 어디에서 할 것인가 : 여기를 확인 하십시오
참고 : 를 지원하지 않는 이전 브라우저의 map
경우 다음과 같이 직접 구현을 추가 할 수 있습니다.
Array.prototype.map = Array.prototype.map || function(_x) {
for(var o=[], i=0; i<this.length; i++) {
o[i] = _x(this[i]);
}
return o;
};
정수로 맵핑하십시오.
a.split(',').map(function(i){
return parseInt(i, 10);
})
map
모든 배열 항목을보고 제공된 함수에 전달하고 해당 함수의 반환 값이있는 배열을 반환합니다. map
이전 브라우저에서는 사용할 수 없지만 jQuery 또는 밑줄 과 같은 대부분의 라이브러리 에는 크로스 브라우저 버전이 포함되어 있습니다.
또는 루프를 선호하는 경우 :
var res = a.split(",");
for (var i=0; i<res.length; i++)
{
res[i] = parseInt(res[i], 10);
}
+string
문자열을 숫자로 변경하려고 시도합니다. 그런 다음 Array.map
함수를 사용 하여 모든 요소를 변경하십시오.
"1,2,3,4".split(',').map(function(el){ return +el;});
더 짧은 해결책 : 인수를 매핑하고 전달하십시오 Number
.
var a = "1,2,3,4";
var b = a.split(',');
console.log(b);
var c = b.map(Number);
console.log(c);
변형으로 lodash 라이브러리 에서 결합 _.map
및 _.ary
메소드를 사용할 수 있습니다 . 전체 변형이 더 간결 해집니다. 공식 문서의 예는 다음과 같습니다 .
_.map(['6', '8', '10'], _.ary(parseInt, 1));
// → [6, 8, 10]
밑줄 js 방법-
var a = "1,2,3,4",
b = a.split(',');
//remove falsy/empty values from array after split
b = _.compact(b);
//then Convert array of string values into Integer
b = _.map(b, Number);
console.log('Log String to Int conversion @b =', b);
There's no need to use lambdas and/or give radix
parameter to parseInt
, just use parseFloat
or Number
instead.
Reasons:
It's working:
var src = "1,2,5,4,3"; var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3] var obj = {1: ..., 3: ..., 4: ..., 7: ...}; var keys= Object.keys(obj); // ["1", "3", "4", "7"] var ids = keys.map(parseFloat); // [1, 3, 4, 7] var arr = ["1", 5, "7", 11]; var ints= arr.map(parseFloat); // [1, 5, 7, 11] ints[1] === "5" // false ints[1] === 5 // true ints[2] === "7" // false ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when
parseInt
-approach - doesn't:// execution time measure function // keep it simple, yeah? > var f = (function (arr, c, n, m) { var i,t,m,s=n(); for(i=0;i++<c;)t=arr.map(m); return n()-s }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now); > f(Number) // first launch, just warming-up cache > 3971 // nice =) > f(Number) > 3964 // still the same > f(function(e){return+e}) > 5132 // yup, just little bit slower > f(function(e){return+e}) > 5112 // second run... and ok. > f(parseFloat) > 3727 // little bit quicker than .map(Number) > f(parseFloat) > 3737 // all ok > f(function(e){return parseInt(e,10)}) > 21852 // awww, how adorable... > f(function(e){return parseInt(e)}) > 22928 // maybe, without '10'?.. nope. > f(function(e){return parseInt(e)}) > 22769 // second run... and nothing changes. > f(Number) > 3873 // and again > f(parseFloat) > 3583 // and again > f(function(e){return+e}) > 4967 // and again > f(function(e){return parseInt(e,10)}) > 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt
works about 4 times faster, but still slower than others. In total: +e
< Number
< parseFloat
< parseInt
Matt Zeunert's version with use arraw function (ES6)
const nums = a.split(',').map(x => parseInt(x, 10));
Array.from() for details go to MDN
var a = "1,2,3,4";
var b = Array.from(a.split(','),Number);
b
is an array of numbers
Since all the answers allow NaN
to be included, I thought I'd add that if you want to quickly cast an array of mixed values to numbers you can do.
var a = "1,2,3,4,foo,bar";
var b = a.split(',');
var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.
// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.
'IT' 카테고리의 다른 글
왜 파이썬에서 @ foo.setter가 작동하지 않습니까? (0) | 2020.06.08 |
---|---|
JSON을 CSV로 변환하려면 어떻게해야합니까? (0) | 2020.06.08 |
스칼라의 연산자 오버로드가 "좋은"것이지만 C ++의 "나쁜"것은 무엇입니까? (0) | 2020.06.08 |
Entity Framework에서 데이터베이스 시간 초과 설정 (0) | 2020.06.08 |
PHP / XAMPP에서 cURL을 활성화하는 방법 (0) | 2020.06.08 |