我正在尝试在 JavaScript 中创建自己的 Set() 方法。但得到意想不到的输出
我有点想为数组中的唯一元素创建自己的 set() 方法作为 mySet() 。但输出错误。 帮帮我。
let arr = [1,2,3,4,5,2,8,1,3,1]
function mySet(arr){
let mapObj = {}
let newArr = []
for (let i = 0; i <arr.length; i++) {
if(mapObj[arr[i]]){
//skip
}else{
mapObj[arr[i]]=i
newArr.push(arr[i])
}
}
return newArr;
}
console.log(mySet(arr)) //i wanted [1,2,3,4,5,8] getting [1,2,3,4,5,8,1]
I'm kind of wanted to create my own set() method as mySet() for unique element from an array. But getting wrong output.
help me out.
let arr = [1,2,3,4,5,2,8,1,3,1]
function mySet(arr){
let mapObj = {}
let newArr = []
for (let i = 0; i <arr.length; i++) {
if(mapObj[arr[i]]){
//skip
}else{
mapObj[arr[i]]=i
newArr.push(arr[i])
}
}
return newArr;
}
console.log(mySet(arr)) //i wanted [1,2,3,4,5,8] getting [1,2,3,4,5,8,1]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您需要对象的真值,可以使用
true
。该检查返回零(第一个索引),结果与您没有为该属性分配任何值相同。
You need a truthy value for the object in this case, you can use
true
.The check returns with zero (the first index) the same result as if you have not assigned any value to the property.
mapObj[arr[i]]=i
分配当前索引。if(mapObj[arr[i]]){
将值视为布尔值。值
1
的第一个索引出现在0
处。所以你说
mapObj[1] = 0
这是假。您需要指定
true
而不是i
。mapObj[arr[i]]=i
assigns the current index.if(mapObj[arr[i]]){
treats the value as a boolean.The first index of the value
1
occurs at0
.So you say
mapObj[1] = 0
which is false.You need to assign
true
instead ofi
.