下面的代码应该接受一个字符串作为输入(这里是inMessage)并分割其中的单词。然后,它会查询 firebase 实时数据库以获取关联的键、值,并用检索到的值替换该单词。这个修改后的字符串必须作为输出发回。
现在,我似乎找不到一种方法使“msg”成为正确的字符串。如果我硬编码一个字符串而不是 msg,我会得到正确呈现的输出。那么如何使 msg 成为正确的字符串呢? (我尝试用“”、toString()、String() 和 JSON.stringify() 将其括起来 - 这里肯定缺少一些东西)
function queryDB(senderID, inMessage){
var arr=inMessage.split(" ");
console.log(arr);
var i;
console.log('inside queryDB');
var msg="";
for(i=0;i<arr.length;i++){
var x = 'https://oreo-fd681.firebaseio.com/'+arr[i]+'.json';
request({
url: x,
method: 'GET'
}, function(error, response, body) {
console.log(response.body);
if (error) {
console.log('Error making api call ' + error);
} else if (response.body.error){
console.log('Error making api call' + response.body.error);
}
else if(response==null) {
//if not found in DB concatenate whatever arr[i] holds
callback1();
}
else {
//else concatenate the found key
var n=JSON.parse(response.body);
//remove the quotes associated with key value
callback2(JSON.stringify(n.key).replace(/['"]+/g, ''));
}
});
function callback1(){
msg+=(arr[i]);
msg+=" ";
console.log(msg);
}
function callback2(add){
msg+=(add);
msg+=" ";
console.log(msg);
}
}
//add quotes back - not sure of this
sendMessageToUser(senderID, ("\""+msg+"\""));
}
最佳答案
这不应该是一个问题。尝试更换
msg+= (arr[i]);
与
msg = msg.concat(arr[i]);
在所有四个 msg +=
赋值中使用 concat
如果您的 arr
值是数值,则可以改为添加数字。
关于javascript - 如何在 Javascript 中连接数组对象和字符串以获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860764/