[英]Extracting numbers from array JavaScript
I have a simple JavaScript question. 我有一个简单的JavaScript问题。 I'm trying to extract numbers from a string where there are two rows separated with '\\n' and each number is separated by ','. 我试图从一个字符串中提取数字,其中有两行用'\\ n'分隔,每个数字都用','分隔。
In the first instance I want to get the first, the second, the third, the fourth and the fifth numbers. 首先,我想获得第一个,第二个,第三个,第四个和第五个数字。 In the second instance I want the first and the sixth numbers. 在第二种情况下,我想要第一个和第六个数字。
My code so far: 到目前为止,我的代码:
var str = "1391,15,48,58,75,9300\n1687,76,65,23,34,9111";
var lines = str.split('\n');
$.each(lines, function () {
var items = str.split(',');
var foo = [],
bar = [],
foobar = str.length;
for (i = 0; i < foobar; i++) {
foo.push([parseFloat(str[i][0]),
parseFloat(str[i][1]),
parseFloat(str[i][2]),
parseFloat(str[i][3]),
parseFloat(str[i][4])
]);
bar.push([parseFloat(str[i][0]),
parseFloat(str[i][5])
]);
}
});
The code does not work. 该代码不起作用。 I only get rubbish out. 我只会把垃圾扔掉。 What am I missing? 我想念什么?
EDIT: 编辑:
To complement Vergilius answer, this code now works: 为了补充Vergilius的答案,现在可以使用以下代码:
var str = "1391,15,48,58,75,9300\n1687,76,65,23,34,9111";
var lines = str.split('\n');
var foo = []; var bar = [];
for(var i = 0; i < lines.length; i++){
var items = lines[i].split(',');
foo.push([parseFloat(items[0]),
parseFloat(items[1]),
parseFloat(items[2]),
parseFloat(items[3]),
parseFloat(items[4])
]);
bar.push([parseFloat(items[0]),
parseFloat(items[5])
]);
}
var str = "1391,15,48,58,75,9300\n1687,76,65,23,34,9111",
lines = str.split('\n'), i, tmp, foo = [], bar = [];
for(i = 0; i <= lines.length - 1; i++) {
tmp = lines[i].split(',');
foo = tmp.filter(function(value, key) { if(key < 5) return true });
bar = tmp.filter(function(value, key) { if(key == 0 || key == 5) return true });
}
should be okay, but you need still to parse items (try with another loop) 应该可以,但是您仍然需要解析项目(尝试使用另一个循环)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.