简体   繁体   English

使用for循环语句了解数组迭代

[英]Understanding array iteration using the for loop statement

So i have this simple script that populates a variable with an array. 所以我有这个简单的脚本,用数组填充变量。 I then use a function with a for loop to iterate trough the array to get it's index values. 然后我使用带有for循环的函数来迭代通过数组来获取它的索引值。

function printAllArrayValues(array) {
    for (var i = 0; i < array.length; i++) {
        var c;
        c += array[i];
    }
    return c;
}
var colorArray = ["brown", "blue", "green"];
alert(printAllArrayValues(colorArray));

The function returns a string containing all the array values but the first value = undefined. 该函数返回一个包含所有数组值的字符串,但第一个值= undefined。 See fiddle: http://jsfiddle.net/vcyum/ 请参阅小提琴: http//jsfiddle.net/vcyum/

Why is that? 这是为什么?

An simpler solution : 更简单的解决方案:

var colorArray = ["brown", "blue", "green"];
alert(colorArray.join('')); // "brownbluegreen"
alert(colorArray.join(',')); // "brown,blue,green"

The initial value of the c variable is undefined . c变量的初始值undefined The next line c += 'stuff' adds the string 'stuff' to the value in c . 下一行c += 'stuff'将字符串'stuff'c的值。 Since the initial value of c is undefined , it is cast to a string, resulting in 'undefined' , so the value of c is now 'undefinedstuff' . 由于c的初始值undefined ,因此它被强制转换为字符串,导致'undefined' ,因此c的值现在是'undefinedstuff'

Your code can be fixed like this: 您的代码可以像这样修复:

function printAllArrayValues(array) {
    var c = '';
    for (var i = 0; i < array.length; i++) {        
        c += array[i];
    }
    return c;
}
var colorArray = ["brown", "blue", "green"];
alert(printAllArrayValues(colorArray));

or simpler: 或者更简单:

var colorArray = ["brown", "blue", "green"];
alert(colorArray.join(''));

To fix your bug, you can change 要修复您的错误,您可以更改

for(var i = 0; i < array.length; i++){
    var c;

to

var c = '';
for(var i = 0; i < array.length; i++){

so that you don't add to undefined (which is transformed to "undefined" in the string concatenation) at the first iteration. 这样你就不会在第一次迭代时添加到undefined (在字符串连接中转换为"undefined" )。

But you could also replace your whole function with colorArray.join('') . 但您也可以使用colorArray.join('')替换整个函数。

Within your loop you declare c , but assign nothing to it. 在你的循环中你声明了c ,但没有为它赋值。 The variable thus has the 'value' undefined . 因此变量具有undefined的“值”。 Now if you add a string to it, undefined is boxed into a string and the string you add is appended to that. 现在,如果向其中添加一个字符串,则将undefined加入一个字符串,并将添加的字符串附加到该字符串中。

Anyway: no need for a loop here: use colorArray.join(''); 无论如何:这里不需要循环:使用colorArray.join(''); for the same result. 为了相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM