本文介绍了如何将字符串拆分()为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应作为数组执行的字符串:

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(',');

如果我使用 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.

推荐答案

一个选项是使用 Number 构造函数,该构造函数返回数字或 NaN :

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]

如果上述情况令人困惑,则可以用Bergi建议的以下条件替换它:

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;

如果要修剪字符串元素,还可以使用 String.prototype.trim 方法:

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;

这篇关于如何将字符串拆分()为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:01