问题
I have a string that should be executed as an array:
var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.split(',');
If I use split()
, it will create an array of strings:
[‘The’, '1', '2', ‘Fox’, ‘Jumped’, '3', ‘Over’, '4']
and I don’t need that. I need an array like:
[‘The’, 1, 2, ‘Fox’, ‘Jumped’, 3, ‘Over’, 4]
indicating which is a string and which is a number.
回答1:
One option is using the Number
constructor which returns a number or NaN
:
var res = q.split(',').map(el => {
let n = Number(el);
return n === 0 ? n : n || el;
});
// > "The, 1, 2, Fox, Jumped, 3.33, Over, -0"
// < ["The", 1, 2, " Fox", " Jumped", 3.33, " Over", -0]
edit: If the above condition is confusing you can replace it with the following condition which was suggested by Bergi:
return isNaN(n) ? el : n;
In case that you want to trim the string elements you can also use the String.prototype.trim
method:
return isNaN(n) ? el.trim() : n;
回答2:
- You can use
Number
function to convert a Stringified number to an actual number. - The
Number
function would returnNaN
, if it is not able to convert a string to a Number.
You can use these two facts to our advantage and write something like this
"The, 1, 2, Fox, Jumped, 3, Over, 4".split(/\s*,\s*/g).map(d => Number(d) || d);
// [ 'The', 1, 2, 'Fox', 'Jumped', 3, 'Over', 4 ]
Since, NaN
is Falsy (Boolean(NaN)
is false
), if the Number
is not able to convert a string to a number, the actual value will be returned as it is.
回答3:
var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.split(',');
You could use Array.map, which returns a new array
var newAr = z.map(item => parseInt(item) ? parseInt(item) : item);
Will output
["The", 1, 2, " Fox", " Jumped", 3, " Over", 4]
回答4:
//from the linked SO answer
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.trim().split(/\s*,\s*/).map(function(word) {
return isNumeric(word) ? Number(word) : word;
});
console.log(z);
How does this work?
isNumeric
It's important to note that you need a way of detecting what is and isn't a number. I suggest using the implementation shown here (the same one as my example) as it's robust and would not throw false positives or false negatives. A lot of the answers here will ignore some valid numbers (e.g., +3
or -3
) or parse something invalid as a number (e.g., ""
).
Let's assume you have a function called isNumeric()
that returns a boolean for whether an input is numeric or not. If need be, you might need to alter the implementation to suit your needs, e.g., if you only want to use whole number or only positive numbers.
Splitting into separate words
The string you have would need to be separated into separate chunks of words. This is done in the following fashion
var input = " The, 1, 2 , Fox , Jumped , 3, Over, 4 ";
input.trim() //make sure there are no beginning and ending spaces
.split(/\s*,\s*/); //split on a comma surrounded by any amount of spaces. That removes spaces from start/end of each of the words
//["The", "1", "2", "Fox", "Jumped", "3", "Over", "4"]
Using .map
The map() method can be ran on an array to transform it into a new array. This us done by transforming each element using a callback function. The callback given simply checks if a word is actually a number - if so, it parses it as a number using Number for explicit type conversion. Note that you should NOT have new Number(word)
as that creates a Number
object, not the numeric primitive type.
It might be useful to note that implicit conversion could be done using the + operator. For example:
+"500" //500
+"hello" //NaN
To the in the beginning of my answer could use +word
instead of Number(word)
but just I find explicit conversion to be easier to understand.
回答5:
This can be achieved by iterating over each of the array items (splitting via the ,
character) and using the map(predict) function. Each of the items can then be tested if they are parseable as an int.
var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.split(',').map(i => !isNaN(parseInt(i)) ? parseInt(i) : i);
Golfed: :)
p=parseInt,q="The, 0 , 2, Fox, Jumped, 3, Over, 4",z=q.split(',').map(i=>!isNaN(p(i))?p(i):i);
回答6:
I gonna be late but checked all the answers and none examined all the cases like: 1.3
, 11 Balls
.. etc. Also you did not trim
the extra whitespaces for the words, and it should be included otherwise we can't get desired result as OP requested.
And parseFloat
is much better because you don't lose decimals:
var q = "The, 1, 2 fd, Fox, 3.12, Jumped, -3, Over, 4";
var z = q.split(',').map(function(i){
i = i.trim();
var reg = /^-?\d+\.?\d*$/;
if (reg.test(i))
return parseFloat(i);
return i;
});
console.log(z);
Result would be:
["The", 1, "2 fd", "Fox", 3.12, "Jumped", -3, "Over", 4]
See the Fiddle
回答7:
A way which takes advantage of +string
conversion to number.
var q = "The, 1, 2, Fox, Jumped, 3, Over, 0";
var r = q.split`, `.map(x=>+x||x==0?+x:x);
console.log(r);
回答8:
I tried loop with forEach
and check is number or not by isNaN:return true if not number,return false if number
push the new array ...
var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = [];
q.split(',').forEach(function(v,k){
isNaN(v) ? z.push(v) : z.push(parseInt(v));
});
console.log(z);
回答9:
You can use for..of
loop, .test()
with /\d/
as parameter
var res = []; for (p of q.split(",")) [...res] = [...res, /\d/.test(p) ? +p : p];
来源:https://stackoverflow.com/questions/38911413/how-to-split-a-string-to-an-array-of-integers