从结果数组 javascript 中获取值
2017-02-12
85
Array[7998]
[0 … 99]
0:" 1 2015-01-14 13:27:07 1 0 2 0"
1:" 1 2015-01-14 13:30:11 1 0 2 0"
2:" 1 2015-01-14 13:33:34 1 0 2 0"
3:" 1 2015-01-14 13:33:43 1 0 2 0"
4:" 2 2015-01-21 10:54:37 1 0 1 0"
5:" 2 2015-02-03 11:39:57 1 0 1 0"
6:" 2 2015-02-03 11:44:56 1 4 1 0"
7:" 1 2015-02-03 11:44:59 1 4 2 0"
8:" 2 2015-02-03 11:49:49 1 0 1 0"
9:" 221 2015-02-03 11:49:51 1 0 1 0"
10:" 221 2015-02-03 11:49:53 1 0 1 0"
11:" 221 2015-02-03 11:52:07 1 0 1 0"
12:" 1 2015-02-26 17:29:24 1 4 2 0"
嗨!我从这段代码中得到了这个结果:
function onReadFile(file){
var txt = file.target.result;
var list = txt.split('\n');
// var result = list.map(function(item){
// return item.split('\n');
// });
console.log(list);
}
有没有办法只获取前三个值或列?前三列代表 ID、日期和时间,所以我只需要提取这三个,就像这样..
[1,2015-01-14,13:27:07][1,2015-01-14,13:30:11][1,2015-01-14,13:33:34][...]
谢谢。
3个回答
var text = " 1 2015-01-14 13:30:11 1 0 2 0\n 1 2015-01-14 13:33:34 1 0 2 0\n 1 2015-01-14 13:33:43 1 0 2 0";
var list =
text.split('\n') // split the lines
.map(function(line) { // map the lines
var parts = line.trim() // trim the current line (remove surrounding spaces)
.split(/\s+/); // split the cols by multiple spaces (space, tabs, ...)
return parts.slice(0, 3); // return an array like your desired output (just the first three cols of each row)
// IF YOU WANT THE RESULT TO BE AN OBJECT THEN REMOVE THE ABOVE RETURN STATEMENT AND UNCOMMENT THE CODE BELLOW
//var o = {};
//o.id = parts[0];
//o.date = parts[1];
//o.time = parts[2];
//return o;
});
console.log(list);
ibrahim mahrir
2017-02-12
您可以使用正则表达式将字符串拆分为多个空格。
var fields = list.split(/\s+/);
console.log(fields);
前三列分别位于索引 1、2 和 3。
Alan
2017-02-12
.match()
个不是空格的字符,
.slice()
结果数组的前三个元素
var list = [" 1 2015-01-14 13:27:07 1 0 2 0"
," 1 2015-01-14 13:30:11 1 0 2 0"
," 1 2015-01-14 13:33:34 1 0 2 0"
," 1 2015-01-14 13:33:43 1 0 2 0"
," 2 2015-01-21 10:54:37 1 0 1 0"
," 2 2015-02-03 11:39:57 1 0 1 0"
," 2 2015-02-03 11:44:56 1 4 1 0"
," 1 2015-02-03 11:44:59 1 4 2 0"
," 2 2015-02-03 11:49:49 1 0 1 0"
," 221 2015-02-03 11:49:51 1 0 1 0"
," 221 2015-02-03 11:49:53 1 0 1 0"
," 221 2015-02-03 11:52:07 1 0 1 0"
," 1 2015-02-26 17:29:24 1 4 2 0"];
var result = list.map(function(text) {
return text.match(/[^\s]+/g).slice(0, 3)
});
console.log(result);
guest271314
2017-02-12