英文:
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(',');
const trimedArr = custOrderArr.map((x) => x.trim());
const numberArr = trimedArr.map((y) => y.split(':'));
const processArr = numberArr.map((z) => 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 = 'name: this is some stuff, name2: this is more stuff ';
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 => s.trim());
An example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let str = 'test: It is me, test2: it is me 2 ';
console.log(str.split(/[\:,]+/).map(s => s.trim()));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论