我正在尝试将python中已有的代码复制到Javascript中,因为这是我的新手,我真的无法找到有关此特定问题的任何参考。 因此,我有一个包含元素的数组,我想查找重复项,但跳过空白空间,但不对其进行过滤,因为在那种情况下,我拥有的计数器会损坏并给我一个错误的值。 数组应为原始形式,而不是排序的。 这是python中的代码:
lis = ["", "5", "2", "", "2", ""]
not_dupl = []
dupl = []
for i in lis:
print(i)
if i not in not_dupl or i =='':
not_dupl.append(i)
else:
dupl.append(i)
print(not_dupl) # expected output ["", "5", "2", "", ""]
print(dupl) # expected output ["2"]
我不确定在javascript中是否存在检查字符串或数组内部的函数“ in”。
答案 0 :(得分:1)
如评论中所述,您正在寻找包含:
const lis = ["", "5", "2", "", "2", ""];
const not_dupl = [], dupl = [];
for(const i of lis) {
console.log(i);
if(!not_dupl.includes(i) || i === '')
not_dupl.push(i);
else
dupl.push(i);
}
console.log(not_dupl, dupl);
PS:i
是非索引的坏名字,还有为什么lis
而不仅仅是list
,为什么是not_dupl
而不是nonDuplicates
呢?
答案 1 :(得分:0)
有两种方法可以执行此操作,可以使用array.includes(object)
或可以检查array.indexOf(object) !== -1
,对于Internet Explorer和Opera中对include的支持相对较差,因此您应该感到厌倦关于使用它。
let lis = ["", "5", "2", "", "2", ""]
let not_dupl = [];
let dupl = [];
lis.forEach((element, index, array) => {
if (element === "" || not_dupl.indexOf(element) === -1) {
not_dupl.push(lis[index]);
} else {
dupl.push(lis[index]);
}
})
console.log(not_dupl); //# expected output ["", "5", "2", "", ""]
console.log(dupl); //# expected output ["2"]
答案 2 :(得分:0)
var mylist = ["", "5", "2", "", "2", ""];
var not_dupl =[];
var dupl = [];
for (var i=0; i< mylist.length; i++){
if (not_dupl.includes(mylist[i]) === false || mylist[i]==='' ){
not_dupl.push(mylist[i])
} else {
dupl.push(mylist[i])
}
}
console.log(not_dupl);
console.log(dupl);
答案 3 :(得分:0)
您可以通过设置来做到这一点:
Javascript:
var lis = ["", "5", "2", "", "2", ""];
var dups = new Set();
var dupl = a.filter(function(i){isDup=dups.has(i);dups.add(i);return isDup && i!=""});