gpt4 book ai didi

javascript - 将 CSV 字符串转换为不带 .split() 的数组

转载 作者:行者123 更新时间:2023-11-30 12:11:05 25 4
gpt4 key购买 nike

我正在尝试想出一个函数,它可以接受任何字符串并输出一个数字和字符串数组,而无需使用 .split()。以下是它需要通过的测试和当前通过测试的功能。我很好奇其他人会如何解决这个问题。

function csvParse(inputString) {
var outputArray = [];
var inputArray = inputString.split(',');
for (var i =0; i < inputArray.length; i++) {
if (!Number.isNaN(+inputArray[i])) {
outputArray.push(+inputArray[i]);
} else {
outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
}
}
return outputArray;
};

describe('CSV Parse', function() {
it('should parse a string of integers correctly', function() {
var input = '3,7,9,1,25';
var output = [ 3, 7, 9, 1, 25 ];
expect(csvParse(input)).to.deep.equal(output);
});
it('should parse a string of strings correctly', function() {
var input = '"3","7","9","1","25"';
var output = ["3", "7", "9", "1", "25"];
expect(csvParse(input)).to.deep.equal(output);
});
it('should parse a string of integers and strings correctly', function() {
var input = '1, "one", 2, "two", 3, "three"';
var output = [1, "one", 2, "two", 3, "three"];
expect(csvParse(input)).to.deep.equal(output);
});
});

最佳答案

基本的 JS 解决方案只是按照您的要求替换 split 方法(fiddle here)

function dumbComaSplit(inputString) {
var strArray = [];
var tmpStr = "";
for (var i = 0; i < inputString.length; i++) {
if (inputString.charAt(i) == ',') {
strArray.push(tmpStr);
tmpStr = "";
continue;
}
tmpStr += inputString.charAt(i);
}
strArray.push(tmpStr);
return strArray;
};

function csvParse(inputString) {
var outputArray = [];
var inputArray = dumbComaSplit(inputString);
for (var i =0; i < inputArray.length; i++) {
if (!Number.isNaN(+inputArray[i])) {
outputArray.push(+inputArray[i]);
} else {
outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
}
}
return outputArray;
};

关于javascript - 将 CSV 字符串转换为不带 .split() 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33786152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com