0
numbers = [1,2,3,4,5];

function doubling(number) {
    number *= 2;
    return number;
}

obj = {};
for (var i = 0; i < numbers.length; i++)
    doubled = doubling(numbers[i]);
    obj[numbers[i]] = doubled;
    console.log(obj);

当我运行我的代码时,它会打印“10”,而我想要它打印 {1:2, 2:4, 3:6, 4:8, 5:10}。为什么会这样?

4

1 回答 1

5
function doubling(number) {
    number *= 2;
    return number;
}

obj = {};

// your problem was here you were missing the curly braces
// so it was only executing the first line in the loop
for (var i = 0; i < numbers.length; i++) {
    doubled = doubling(numbers[i]);
    obj[numbers[i]] = doubled;
}
console.log(obj);

你原来的循环基本上是这样的......

for (var i = 0; i < numbers.length; i++) {
    doubled = doubling(numbers[i]);
}
obj[numbers[i]] = doubled;  // numbers[i] is undefined so it 
                            // sets obj[undefined] = 10 
                            // (the value of double after the loop)
console.log(obj);
于 2013-06-28T16:52:00.413 回答