gpt4 book ai didi

javascript for 循环 - 如何获取 [i] 之前的文本

转载 作者:行者123 更新时间:2023-12-03 06:02:42 25 4
gpt4 key购买 nike

我正在尝试创建一个解析器来将坐标数据解析为 json。数据位于简单 x,y 格式的文本文件中。我正在尝试获取 [i] 之前的文本,可以使用 .split() 吗?

代码:

function visualize()
{
if(currDoc == null)
{
var location = window.prompt("Please enter the name of the dataset file, and make sure it is in the data directory. Current supported formats txt.");
location = "data/" + location;
jQuery.get(location, function(data) {
data = data.replace(/\s/g, '');
var length = data.length;
var commaCount = 0;
for(var i=0;i<length;i++)
{
if(data[i] == ",")
{
commaCount += 1;
if(commaCount == 2)
{
//get text before [i]
}
}
}
}, "text").fail(function(){ alert("File not found. Did you enter the file name correctly?") });
}
else
{
alert("A dataset is already visualized");
}
}

最佳答案

如果您的数据以逗号分隔,例如 x1,y1,x2,y2,...,xn,yn,您可以使用 split 函数来拆分数据字符串转换为标记。然后您可以迭代它们以从输入中收集您需要的任何内容。

例如,如果您需要 x 和 y 对,您将执行以下操作:

function visualize()
{
if(currDoc == null)
{
var location = window.prompt("Please enter the name of the dataset file, and make sure it is in the data directory. Current supported formats txt.");
location = "data/" + location;
jQuery.get(location, function(data) {
data = data.replace(/\s/g, '');

// split the string 'x1,y1,...,xn,yn' into tokens ['x1', 'y1', ... 'xn', 'yn']
var tokens = data.split(',');

// iterate over all tokens using a step of 2 (i += 2)
// Note: if you have an odd number of tokens the last one will be ignored
// (this is by design because you are expecting x,y pairs)
for(var i = 1; i < tokens.length; i += 2)
{
// print the (x,y) pair to the console
console.log("New pair (" + tokens[i-1] + "," + tokens[i] + ")");
}
}, "text").fail(function(){ alert("File not found. Did you enter the file name correctly?") });
}
else
{
alert("A dataset is already visualized");
}
}

关于javascript for 循环 - 如何获取 [i] 之前的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39690341/

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