我以这种方式接收数据:
[Sun Jan 01 2006 00:00:00 GMT-0600 (CST), 8.605613643557573, 0]
[Mon Jan 01 2007 00:00:00 GMT-0600 (CST), 4.639263458390814, 0]
[Tue Jan 01 2008 00:00:00 GMT-0600 (CST), 3.690424190442011, 0]
[Thu Jan 01 2009 00:00:00 GMT-0600 (CST), -6.068362055704255, 0]
[Fri Jan 01 2010 00:00:00 GMT-0600 (CST), 0.011317380895792274, 0]
[Sat Jan 01 2011 00:00:00 GMT-0600 (CST), 3.9984661908088825, 0]
[Sun Jan 01 2012 00:00:00 GMT-0600 (CST), 2.4211622308876173, 0]
[Tue Jan 01 2013 00:00:00 GMT-0600 (CST), -1.5740599423273804, 0]
[Wed Jan 01 2014 00:00:00 GMT-0600 (CST), 2.6624793033769967, 0]
[Thu Jan 01 2015 00:00:00 GMT-0600 (CST), 1744.9379869455643, 0]
["err", NaN]
[Wed Jan 01 2020 00:00:00 GMT-0600 (CST),0 , 3417.1886283181875]
[Wed Jan 01 2025 00:00:00 GMT-0600 (CST),0 , 3331.7059850696196]
[Tue Jan 01 2030 00:00:00 GMT-0600 (CST),0 , 3237.940431993671]
我正在尝试使数据集看起来像这样:
Product | Action | Response
------------------------------
a |POST | NULL
b |PUT | NULL
c |DEL | NULL
d |POST | NULL
e |PUT | NULL
f |DEL | NULL
有没有办法通过查看“错误”的索引来做到这一点?
答案 0 :(得分:2)
您可以使用变量来跟踪是否找到了"err"
,并使用该信息来确定.splice()
新成员的位置。
var found = false
for (const a of data) {
if (!found && a[0] === "err")
found = true;
else
a.splice(found ? 1 : 2, 0, 0);
}
如果要使用找到err
的索引,请在数组上使用.entries()
并更改found
变量以存储索引。
var foundIdx = -1;
for (const [idx, a] of data.entries()) {
const found = foundIdx !== -1;
if (!found && a[0] === "err")
foundIdx = idx;
else
a.splice(found ? 1 : 2, 0, 0);
}
console.log("the err index was", foundIdx);
答案 1 :(得分:0)
您可以使用findIndex
查看错误索引:
var errIndex = data.findIndex(el => el[0] == "err");
assert(errIndex != -1);
return data.map(([date, val], i) => {
if (i < errIndex)
return [date, val, 0];
if (i > errIndex)
return [date, 0, val];
return ["err", NaN] // or whatever
);
或者你可能想要
var it = data.values();
for (const el of it) {
if (el[0] == "err") break;
el.push(0);
}
for (const el of it) {
el.splice(1, 0, 0);
}