我正在使用javascript Stomp客户端在服务器发送消息时进行订阅。
我需要创建一个新的订阅消息数组。每条消息都有不同的ID。如果id存在,则不会推送任何内容,但如果数组不存在,则新对象将被推送到空数组。
这就是我所尝试的
CODE:
var recivedData = []
connect()
function connect() {
var socket = new SockJS('/info-app');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/info', function (msg) {
var parsedData = JSON.parse(msg.body)
if(!(recivedData.length)){
recivedData.push(parsedData)
console.log(recivedData)
}
if(recivedData.length){
if(recivedData.find(e => e.id === parsedData.id)){
console.log(" there")
console.log(recivedData)
}
if(recivedData.find(e => e.id !== parsedData.id)){
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});
});
}
每当新的id进入时,它都会推送到数组,但是如果再次输入相同的id,它也会推送。
我该如何解决?提前谢谢
答案 0 :(得分:2)
在将数据推入第一个空数组后,您不希望执行if(recivedData.length){
阻止。使用else
语句的if
部分:
stompClient.subscribe('/topic/info', function(msg) {
var parsedData = JSON.parse(msg.body)
if (!recivedData.length) {
recivedData.push(parsedData)
console.log(recivedData)
} else {
if (recivedData.some(e => e.id === parsedData.id)) {
console.log(" there")
console.log(recivedData)
} else {
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});