如何将字符串分割成一个整数数组

时间:2021-04-08 21:35:19

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:

如果我使用split(),它将创建一个字符串数组:

[‘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.

指示哪个是字符串,哪个是数字。

9 个解决方案

#1


14  

One option is using the Number constructor which returns a number or NaN:

一个选项是使用数字构造函数返回一个数字或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:

编辑:如果上面的条件让你感到困惑,你可以用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:

如果您想要修剪字符串元素,您还可以使用string .prototype。调整方法:

return isNaN(n) ? el.trim() : n;

#2


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., "").

需要注意的是,您需要一种方法来检测什么是数字,什么不是数字。我建议使用这里显示的实现(与我的示例相同),因为它是健壮的,不会抛出假阳性或假阴性。这里的许多答案会忽略一些有效的数字(例如+3或-3)或将一些无效的东西解析为数字(例如,“”)。

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.

让我们假设您有一个名为isNumeric()的函数,它为输入是否为数值返回一个布尔值。如果需要的话,您可能需要修改实现以满足您的需要,例如,如果您只想使用整数或正数。

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.

可以在数组上运行map()方法,将其转换为新的数组。这是通过使用回调函数来转换每个元素完成的。所给出的回调只是检查一个单词是否是一个数字——如果是,它将它解析为一个数字,使用数字进行显式类型转换。注意,不应该有新的数字(单词),因为这会创建数字对象,而不是数字原语类型。

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.

我的答案开头可以用+word代替Number(word),但我发现显式转换更容易理解。

#3


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

您可以使用数组。map,返回一个新的数组

var newAr = z.map(item => parseInt(item) ? parseInt(item) : item); 

Will output

将输出

["The", 1, 2, " Fox", " Jumped", 3, " Over", 4]

["The", 1,2, " Fox", " jump ", 3, " Over", 4]

#4


3  

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.

这可以通过遍历每个数组项(通过字符分割)和使用map(预测值)函数来实现。每一个项目都可以测试,如果它们可以作为一个整数。

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);

#5


3  

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.

我要迟到了,但我检查了所有的答案,没有人检查所有的案例,比如:1.3,11个球。等。另外,你没有为字词修剪额外的白空格,应该包括在内,否则我们无法得到预期的结果。

And parseFloat is much better because you don't lose decimals:

parseFloat属性更好,因为你不会损失小数

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

看到小提琴

#6


3  

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);

#7


3  

  1. You can use Number function to convert a Stringified number to an actual number.
  2. 可以使用Number函数将字符串转换为实际数字。
  3. The Number function would return NaN, if it is not able to convert a string to a Number.
  4. 如果不能将字符串转换为数字,那么Number函数将返回NaN。

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.

因为NaN是Falsy (Boolean(NaN)是false),如果这个数字不能将一个字符串转换为一个数字,那么实际的值将返回原样。

#8


2  

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 ...

我试着用forEach循环并检查是否由isNaN:返回true如果不是number,返回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


2  

You can use for..of loop, .test() with /\d/ as parameter

你可以使用. .循环的。test()和/\d/作为参数

var res = []; for (p of q.split(",")) [...res] = [...res, /\d/.test(p) ? +p : p];

#1


14  

One option is using the Number constructor which returns a number or NaN:

一个选项是使用数字构造函数返回一个数字或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:

编辑:如果上面的条件让你感到困惑,你可以用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:

如果您想要修剪字符串元素,您还可以使用string .prototype。调整方法:

return isNaN(n) ? el.trim() : n;

#2


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., "").

需要注意的是,您需要一种方法来检测什么是数字,什么不是数字。我建议使用这里显示的实现(与我的示例相同),因为它是健壮的,不会抛出假阳性或假阴性。这里的许多答案会忽略一些有效的数字(例如+3或-3)或将一些无效的东西解析为数字(例如,“”)。

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.

让我们假设您有一个名为isNumeric()的函数,它为输入是否为数值返回一个布尔值。如果需要的话,您可能需要修改实现以满足您的需要,例如,如果您只想使用整数或正数。

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.

可以在数组上运行map()方法,将其转换为新的数组。这是通过使用回调函数来转换每个元素完成的。所给出的回调只是检查一个单词是否是一个数字——如果是,它将它解析为一个数字,使用数字进行显式类型转换。注意,不应该有新的数字(单词),因为这会创建数字对象,而不是数字原语类型。

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.

我的答案开头可以用+word代替Number(word),但我发现显式转换更容易理解。

#3


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

您可以使用数组。map,返回一个新的数组

var newAr = z.map(item => parseInt(item) ? parseInt(item) : item); 

Will output

将输出

["The", 1, 2, " Fox", " Jumped", 3, " Over", 4]

["The", 1,2, " Fox", " jump ", 3, " Over", 4]

#4


3  

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.

这可以通过遍历每个数组项(通过字符分割)和使用map(预测值)函数来实现。每一个项目都可以测试,如果它们可以作为一个整数。

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);

#5


3  

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.

我要迟到了,但我检查了所有的答案,没有人检查所有的案例,比如:1.3,11个球。等。另外,你没有为字词修剪额外的白空格,应该包括在内,否则我们无法得到预期的结果。

And parseFloat is much better because you don't lose decimals:

parseFloat属性更好,因为你不会损失小数

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

看到小提琴

#6


3  

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);

#7


3  

  1. You can use Number function to convert a Stringified number to an actual number.
  2. 可以使用Number函数将字符串转换为实际数字。
  3. The Number function would return NaN, if it is not able to convert a string to a Number.
  4. 如果不能将字符串转换为数字,那么Number函数将返回NaN。

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.

因为NaN是Falsy (Boolean(NaN)是false),如果这个数字不能将一个字符串转换为一个数字,那么实际的值将返回原样。

#8


2  

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 ...

我试着用forEach循环并检查是否由isNaN:返回true如果不是number,返回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


2  

You can use for..of loop, .test() with /\d/ as parameter

你可以使用. .循环的。test()和/\d/作为参数

var res = []; for (p of q.split(",")) [...res] = [...res, /\d/.test(p) ? +p : p];