Javascript: "undefined" 变量值

Javascript: "undefined" value for variable

newbee 到 Javascript...

我在使用函数结果更新全局变量时遇到问题。当我输出变量时,它说'undefined'。

我想做的是遍历数组 (problemArr) 并在变量 (stringA)。

然后将stringA添加到另一个变量stringMessage,输出stringMessage的值。

例如:您最大的问题是:问题 1、问题 2、问题 3,

我已经有一个名为 problemArr 的数组,它是从另一个我没有包含在这段代码中的函数更新的。 (这部分有效,我能够证明数组已更新)。

我在这里读了一些关于函数范围和提升的帖子,我认为这可能与它有关。不确定。

var stringA = ' ';//initialize variable which will form list of problems 

var stringMessage ='Your biggest problems are :' + stringA; // Output

var problemArr[]; //Empty array. Gets elements from another function - this part works, I've checked. 

//create list of problems
function messageString(){

    for(i in problemArr){

        stringA = stringA + problemArr[i] + ',';
    }

    return stringA;

}

你需要定义你的数组,它是missng,然后调用你创建的函数如下。

var stringA = ' ';//initialize variable which will form list of problems 

var problemArr = ['1','2','3']; // <<<<<<<<< define the array

//create list of problems
function messageString(){

    for(i in problemArr){

        stringA += problemArr[i] ; 
        
        // do not add a comma after the last array item
        if(i < problemArr.length - 1)
        {
           stringA  += ',';
        }
    }

}

messageString(); // <<<<<<<<< call the function

var stringMessage ='Your biggest problems are :' + stringA; // Output

document.write(stringMessage);

编辑

为匹配您的情况,调用函数创建消息字符串并填充 stringA,然后将其设置为最终输出 var stringMessage ='Your biggest problems are :' + stringA; // Output

您似乎只是想将数组的内容添加到字符串变量中。你为什么不这样做呢:

var problemArr = ["99 problems","but a b****","ain't one"];
//or just use the array you created before

var problemsAsString = problemArr.join(", ");
//converts the array to a string and puts a ", " between each element

var stringMessage = 'Your biggest problems are : ' + problemsAsString; 

alert(stringMessage); //output, or do whatever you want with it

JSFiddle

尝试用字符串替换字符串,字符串始终必须是一个新变量,因此您需要的不是 stringA = stringA,而是 newString = stringA + ","

我已经重构了你的代码,这将完成你想要它做的事情:

(function () {
    var stringA;
    var stringMessage = "Your biggest problems are : ";
    var problemArr = [1, 2, 3, 4, 5, 6];

    for (var i = 0; i < problemArr.length; i++) {
        stringA = problemArr[i] + ",";
        stringMessage += stringA;
    }

    alert(stringMessage);

})()

“+=”运算符将某些内容附加到现有对象 例如 1 += 2 等于 3 例如 "hello" += "world" 等于 "helloworld"