2013-06-28 47 views
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); 

當我運行我的代碼,它打印的時候我要的是它打印{1「10」:2,2:4, 3:6,4:8,5:10}。爲什麼會發生?如何寫入雙號的功能,並通過他們作爲一個對象

+2

您for循環中缺少{} –

+0

爲巴斯說:http://jsfiddle.net/LW6z7/正常工作 –

+0

沒有捲曲大括號,for循環僅在它之後直接循環。另請參閱:https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript#Control_structures –

回答

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); 
+0

也許是一句解釋...? –

+1

新增解釋 - 作爲一般的經驗法則,我從不使用無花括號的速記,因爲它也曾經咬過我。 –

+0

這是一個要記住的重要一點,謝謝! – bard

相關問題