简体   繁体   English

如何拆分 javascript 数组并替换其中的元素?

[英]How can I split a javascript array and replace elements of it?

updated I'm quite a new to this.更新我对此很陌生。 I have looked everywhere and tried everything under the sun to fix this on my own.我到处寻找,并尝试了一切在阳光下自己解决这个问题。 My data is from a text input where i need to read specific line.我的数据来自我需要读取特定行的文本输入。 My code reads the lines perfectly using the slice(2,1) method.我的代码使用 slice(2,1) 方法完美地读取了这些行。 Now I need to use the data to do other things.现在我需要使用这些数据来做其他事情。

my extracted string from reading data lines from 3rd line data till 2nd last line, and this already works:我从第 3 行数据到最后第 2 行读取数据行中提取的字符串,这已经有效:

var x = readData.slice(2,-1).toString(); var x = readData.slice(2,-1).toString();

Output using console.log(x); Output 使用 console.log(x); //0 1,2 3,4 5 as it should be //0 1,2 3,4 5 应该是这样

but I want: '0,1','2,3','4,5'但我想要:'0,1','2,3','4,5'

So that i can use this data to do other things.这样我就可以使用这些数据来做其他事情。

I have tried:我努力了:

var x = readData.slice(2,-1).toString().split(' ',-1); var x = readData.slice(2,-1).toString().split(' ',-1);

this gives me: [ '0', '1,2', '3,4', '5' ] //which is the closest这给了我: [ '0', '1,2', '3,4', '5' ] //这是最接近的

i have also tried:我也试过:

var x = readData.slice(2,-1).toString().replace(/\s/g, ', ').split(" ", -1); var x = readData.slice(2,-1).toString().replace(/\s/g, ', ').split(" ", -1); which gives [ '0,', '1,2,', '3,4,', '5' ]这给出了 ['0,', '1,2,', '3,4,', '5']

var x = [x.split(' ').join(',')]; var x = [x.split('').join(',')]; which gives [ '0,1,2,3,4,5' ]这给出了 ['0,1,2,3,4,5']

and a few other combos too.以及其他一些组合。 Can anyone please help?有人可以帮忙吗?

According to the following statement根据以下说法

.replace(/\s/g, ', ').split(" ", -1); which gives [ '0,', '1,2,', '3,4,', '5' ]

in the question, this 0 1,2 3,4 5 is a string, so you can split by comma and then map the strings according to the desired output在问题中,这个0 1,2 3,4 5是一个字符串,所以你可以用逗号分隔然后 map 根据所需的 output 字符串

 console.log("0 1,2 3,4 5".split(",").map(s => s.split(/\s+/g).join(",")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM