Using trim more than once in an array JS

huangapple go评论80阅读模式
英文:

Using trim more than once in an array JS

问题

trim函数第一次起作用,但第二次不起作用是因为您尝试在一个数组上调用trim函数,而不是在字符串上调用它。在第一次使用trim时,您是在字符串上调用它,因为您在custOrderArr.map()内的每个元素上使用了trim()。但是,在第二次使用trim时,您尝试在数组numberArr的每个子数组上调用它,这是不正确的,因为数组上没有trim方法。

如果您想在每个子数组的第二个元素上使用trim,可以像这样修改代码:

function parseOrder(custOrder) {
  const custOrderArr = custOrder.split(',');
  const numberArr = custOrderArr.map((x) => x.trim().split(':'));
  console.log(numberArr);
}

这将在每个子数组的第二个元素上使用trim,并且应该达到您期望的输出。

英文:

I have a snippet of code where I am trying to parse a longer string with special characters into an array with no spaces or special characters.
<br>input: name: this is some stuff, name2: this is more stuff
<br>desired output: [name,this is some stuff,name2,this is more stuff]
<br>current output: z.trim isn't a function

function parseOrder(custOrder) {
  const custOrderArr = custOrder.split(&#39;,&#39;); 
  const trimedArr = custOrderArr.map((x) =&gt; x.trim());
  const numberArr = trimedArr.map((y) =&gt; y.split(&#39;:&#39;));
  const processArr = numberArr.map((z) =&gt; z.trim());
  console.log(processArr);
}

Why does trim work the first time and not the second?

答案1

得分: 2

你不能修剪一个数组,但你可以映射该数组并修剪值。

这个结果使用 Array#flatMap 防止数组包含对。

function parseOrder(custOrder) {
    return custOrder
        .split(',')
        .flatMap(y => y.split(':').map(x => x.trim()));
}

var input = 'name: this is some stuff, name2: this is more stuff ';

console.log(parseOrder(input));

(请注意:此回答仅包含翻译的内容,没有其他信息。)

英文:

You can not trim an array. But you could map the array and trim the values.

This result features Array#flatMap for preventing arrays with pairs.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function parseOrder(custOrder) {
return custOrder
.split(',')
.flatMap(y => y.split(':').map(x => x.trim()));
}

var input = &#39;name: this is some stuff, name2: this is more stuff &#39;;

console.log(parseOrder(input));

<!-- end snippet -->

答案2

得分: 1

尝试通过两个符号进行split,然后trim您的元素:

const result = str.split(/[\:,]+/).map(s => s.trim());

一个示例:

let str = 'test: It is me, test2: it is me 2 ';
console.log(str.split(/[\:,]+/).map(s => s.trim()));
英文:

Try to split by two signs, then trim your elements:

const result = str.split(/[\:,]+/).map(s =&gt; s.trim());

An example:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let str = &#39;test: It is me, test2: it is me 2 &#39;;
console.log(str.split(/[\:,]+/).map(s =&gt; s.trim()));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月7日 00:21:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定