如何连接数组对象和字符串以获得Javascript中的字符串?
下面的代码应该将一个字符串作为输入(此处为inMessage)并拆分其中的单词。然后,它查询firebase实时数据库中的相关键、值,并用检索到的值替换该单词。此修改后的字符串必须作为输出返回 现在,我似乎找不到一种方法使“msg”成为一个合适的字符串。如果我硬编码一个字符串而不是msg,我会得到正确呈现的输出。那么如何使msg成为一个合适的字符串呢?(我试着用“”、toString()、String()和JSON.stringify()来封装它-这里一定缺少一些东西)如何连接数组对象和字符串以获得Javascript中的字符串?,javascript,string,firebase,Javascript,String,Firebase,下面的代码应该将一个字符串作为输入(此处为inMessage)并拆分其中的单词。然后,它查询firebase实时数据库中的相关键、值,并用检索到的值替换该单词。此修改后的字符串必须作为输出返回 现在,我似乎找不到一种方法使“msg”成为一个合适的字符串。如果我硬编码一个字符串而不是msg,我会得到正确呈现的输出。那么如何使msg成为一个合适的字符串呢?(我试着用“”、toString()、String()和JSON.stringify()来封装它-这里一定缺少一些东西) 函数queryDB(se
函数queryDB(senderID,inMessage){
var arr=inMessage.split(“”);
控制台日志(arr);
var i;
console.log('insidequerydb');
var msg=“”;
对于(i=0;i这应该不是问题。请尝试替换
msg+= (arr[i]);
与
在所有四个msg+=
分配中使用concat
如果您的arr
值是数值,则可以改为添加数字。您的问题与请求
回调的异步性质有关:
- 在任何请求返回结果之前执行
sendMessageToUser
- 因为
i
是用var
声明的,i
的值将在任何请求返回结果之前达到arr.length
,因此在callback1
中,该值将无效——它将始终引用未定义的arr[arr.length]
- 假设返回的键是字符串,没有理由首先将它们字符串化为JSON,然后删除引号。事实上,如果键包含引号,那么这些引号将在该过程中丢失
- 无法保证对请求的响应将以相同的顺序返回。因此,执行
msg+=
很可能会生成一个键顺序错误的字符串
- 这不是一个bug,但是在循环中创建函数应该保持在最低限度。所以我不会像那样使用
callback1
和callback2
下面是一种方法,它坚持普通的旧回调模式。它有以下更改:
- 它首先收集数组中的键,这样您就可以将键精确地放在它所属的索引处。这样一来,响应的顺序就无关紧要了;数组最后仍然会以正确的顺序保存它们
- 它记录了我们仍在等待的响应数量。这样,您就可以知道何时收到所有响应,然后调用
sendMessageToUser
- 变量
i
在for
构造中用let
声明,因此它有块作用域,也就是说,每次循环迭代都会得到一个单独的变量。这样,当您在回调中引用它时,它将恰好指向该版本的变量
callback1
和callback2
函数被替换为可以处理这两种变化的代码(当response===null
或不时)
代码如下:
function queryDB(senderID, inMessage){
var arr = inMessage.split(" ");
console.log(arr);
console.log('inside queryDB');
// At first, use an array, so you can put back the asynchronous results in the correct order
var msgArray = [];
// Keep track of the number of asynchronous results you are still waiting for
var leftOver = arr.length;
// Use LET to make loop variable block scoped: that way you'll have the same value for
// it when the asynchronous callback is called
for(let 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 {
// Treat the two cases with the ternary operator
// and put the result at the correct index
msgArray[i] = response === null ? arr[i] : JSON.parse(response.body).key;
console.log(msgArray);
// Detect when you have collected all results
leftOver--;
if (!leftOver) {
// Join all the words together into one string and send it
sendMessageToUser(senderID, msgArray.join(' '));
}
}
});
}
}
函数queryDB(senderID,inMessage){
var arr=inMessage.split(“”);
控制台日志(arr);
console.log('insidequerydb');
//首先,使用一个数组,这样就可以按正确的顺序返回异步结果
var msgArray=[];
//跟踪您仍在等待的异步结果的数量
var剩余=arr.length;
//使用LET设置循环变量块的作用域:这样,您将拥有相同的
//它在调用异步回调时发生
for(设i=0;i
正如我所说,我坚持回调模式,但是当你使用承诺和Promise.all
方法时,事情会变得更好。你应该仔细研究一下。这很有魅力!谢谢@trincot:)你没有在你的代码中声明“n”。我将研究承诺。真主,是的,我现在用它应该是的表达式替换了n
。
msg = msg.concat(arr[i]);
function queryDB(senderID, inMessage){
var arr = inMessage.split(" ");
console.log(arr);
console.log('inside queryDB');
// At first, use an array, so you can put back the asynchronous results in the correct order
var msgArray = [];
// Keep track of the number of asynchronous results you are still waiting for
var leftOver = arr.length;
// Use LET to make loop variable block scoped: that way you'll have the same value for
// it when the asynchronous callback is called
for(let 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 {
// Treat the two cases with the ternary operator
// and put the result at the correct index
msgArray[i] = response === null ? arr[i] : JSON.parse(response.body).key;
console.log(msgArray);
// Detect when you have collected all results
leftOver--;
if (!leftOver) {
// Join all the words together into one string and send it
sendMessageToUser(senderID, msgArray.join(' '));
}
}
});
}
}