javascript 在循环中连接 var

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8792604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:35:45  来源:igfitidea点击:

concatenate var in loop

javascript

提问by user947462

A basic question please, I am trying this code:

请提出一个基本问题,我正在尝试以下代码:

var number_questions = postsJSON1[i]['question'].length;
for (a=0; a<number_questions; a++) {
var post+[a] = postsJSON1[i]['question'][a];    
}

this line give an error: var post+[a]

这一行给出了一个错误: var post+[a]

What is the correct way ?

什么是正确的方法?

回答by PeeHaa

This will get you an array:

这将为您提供一个数组:

var number_questions = postsJSON1[i]['question'];
var post = [];
for (a=0; a<number_questions; a++) {
  post[a] = postsJSON1[i]['question'][a];    
}

This will get you a string:

这会给你一个字符串:

var number_questions = postsJSON1[i]['question'];
var post = '';
for (a=0; a<number_questions; a++) {
  post += postsJSON1[i]['question'][a];    
}

BTW I don't know the contents of postsJSON1[i]['question'], but the following looks a bit weird:

顺便说一句,我不知道 的内容postsJSON1[i]['question'],但以下内容看起来有点奇怪:

var number_questions = postsJSON1[i]['question'];

Shouldn't that be:

不应该是:

var number_questions = postsJSON1[i]['question'].length;

?

?

回答by Wayne

It's hard to see exactly what you're trying to do, but I think you want this:

很难确切地看到你想要做什么,但我认为你想要这个:

var number_questions = postsJSON1[i]['question'].length;
var post = "";
for (a = 0; a < number_questions; a++) {
    post += postsJSON1[i]['question'][a];    
}

I'm assuming that postsJSON1[i]['question']is an array, since you're treating it as such in the body of the loop. That's why I've changed the first line to use the lengthproperty to init number_questions.

我假设这postsJSON1[i]['question']是一个数组,因为您在循环体中是这样对待它的。这就是为什么我将第一行更改为使用该length属性的原因 init number_questions

By the way, this code is functionally equivalent to join; you could do the same thing in one line:

顺便说一下,这段代码在功能上等同于join; 你可以在一行中做同样的事情:

var post = postsJSON1[i]['question'].join("");