如何从JavaScript中的数组中删除拼接列表? [英] How to remove list of splices from array in JavaScript?
问题描述
我有索引列表:
var remove_list = [ [ 7, 12 ], [ 12, 14 ] ];
以及Scheme Lisp中S-Expression的标记列表.
and list of tokens of S-Expression from Scheme lisp.
var tokens = [
'(', 'let', '(', '(',
'x', '10', ')', '#;',
'(', 'foo', 'bar', ')',
'#;', 'xxx', ')', '(',
'*', 'x', 'x', ')',
')'
];
从令牌中删除所有项目的最佳方法是什么.(它假定按照R7RS中的指定删除内联命令#;(foo bar)
ad #; xxx
).
what is the best way to remove all items from tokens. (it suppose to remove inline commands #;(foo bar)
ad #;xxx
as specified in R7RS).
我可以使用这个
for (let remove of remove_list) {
tokens.splice(...remove);
}
因为在第一次调用拼接索引后将发生变化.从数组中删除所有指定范围的最简单方法是什么?
because after first call to splice indexes will change. What is simplest way to remove all specified ranges from array?
在上下文中,我具有应删除内联注释的功能,因此我从将索引从数组中删除的方式拆分了计算方法,这是一种好方法吗?
And for context I have this function that should remove inline comments, I've splitted calculating the indexes from removing them from array, is this good approach?
function strip_s_comments(tokens) {
var s_count = 0;
var s_start = null;
var remove_list = [];
for (let i = 0; i < tokens.length; ++i) {
const token = tokens[i];
if (token === '#;') {
if (['(', '['].includes(tokens[i + 1])) {
s_count = 1;
s_start = i;
} else {
remove_list.push([i, i + 2]);
}
i += 1;
continue;
}
if (s_start !== null) {
if ([')', ']'].includes(token)) {
s_count--;
} else if (['(', '['].includes(token)) {
s_count++;
}
if (s_count === 0) {
remove_list.push([s_start, i + 1]);
s_start = null;
}
}
}
for (let remove of remove_list) {
tokens.splice(...remove);
}
return tokens;
}
推荐答案
您有两个选择:
-
以相反的顺序工作,或者
Work in reverse order, or
跟踪删除的内容,并在以后的索引中加以考虑
Keep track of how much you've removed and take that into account with later indexes
这里是#1的示例:
const reverse = remove_list.sort(([a], [b]) => b - a);
for (const [begin, end] of reverse) {
tokens.splice(begin, end - begin);
}
var remove_list = [ [ 7, 12 ], [ 12, 14 ] ];
var tokens = [
'(', 'let', '(', '(',
'x', '10', ')', '#;',
'(', 'foo', 'bar', ')',
'#;', 'xxx', ')', '(',
'*', 'x', 'x', ')',
')'
];
const reverse = remove_list.sort(([a], [b]) => b - a);
for (const [begin, end] of reverse) {
tokens.splice(begin, end - begin);
}
console.log(tokens);
这里是#2的示例:
let removed = 0;
for (const [begin, end] of remove_list) {
removed += tokens.splice(begin - removed, end - begin).length;
}
var remove_list = [ [ 7, 12 ], [ 12, 14 ] ];
var tokens = [
'(', 'let', '(', '(',
'x', '10', ')', '#;',
'(', 'foo', 'bar', ')',
'#;', 'xxx', ')', '(',
'*', 'x', 'x', ')',
')'
];
let removed = 0;
for (const [begin, end] of remove_list) {
removed += tokens.splice(begin - removed, end - begin).length;
}
console.log(tokens);
这篇关于如何从JavaScript中的数组中删除拼接列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!