无法在函数内更改

无法在函数内更改

本文介绍了无法在函数内更改 JSON 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段更改 JSON 变量失败:

Altering a JSON variable is failing for following snippet:

var data = {status: ''};

rosconnection.setOnOpen(function (e) {
        data.status = 'Succeeded';
        alert('success');
});

rosconnection.setOnError(function (e) {
        data.status = 'Failed';
        alert('fail');
});

data 保持为空,但 alertrosconnection.setOnOpen 中被调用.该错误很难复制,因此它用于 ros 连接,但我 100% 肯定它至少成功进入了其中一个功能.

data stays empty, but the alert gets called within rosconnection.setOnOpen. The error is hard to replicate hence its used on a ros connection, but i am 100% certain that it enters atleast one of the functions with success.

推荐答案

你没有告诉我们你是如何知道状态没有改变所以...

You didn't show us how you know the status didn't change so...

我敢打赌:如果 data 没有改变,你就不可能看到警报,所以你的代码可能看起来像这样:

My bet is: there is no way you saw the alert without the data being changed so your code probably looks something like this:

var data = {status: ''};

rosconnection.setOnOpen(function (e) {
        data.status = 'Succeeded';
        alert('success');
});

rosconnection.setOnError(function (e) {
        data.status = 'Failed';
        alert('fail');
});

alert(data.status);

所以状态还没有设置.在回调中检查它.AJAX...
AJAX 是什么意思?A 代表异步,这意味着它会在未来某个时间(近或远)触发,你不知道什么时候,有时甚至不知道它是否会被调用.

So the status was not set yet. Check it inside the callback. AJAX...
What does AJAX means? A is for async, which means it will fire sometime in the future(near or far), you can't know when and sometimes don't even if it will ever be called.

更新版本:

var data = {status: ''};

rosconnection.setOnOpen(function (e) {
        data.status = 'Succeeded';
        alert(data.status);
});

rosconnection.setOnError(function (e) {
        data.status = 'Failed';
        alert(data.status);
});

这篇关于无法在函数内更改 JSON 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 18:16