2013-09-25 119 views

回答

2

使用parseInt

numbers[0]將返回一個字符串值。因爲odd是數組數組, 找不到它的索引。因此,使用parseInt

jsFiddle Demo

numbers = document.getElementById("inputfield").value; 
var x = parseInt(numbers[0]); 
alert(odd.indexOf(x)); 
3

這是因爲number[0]undefined

var number = 1; 
var array = [ "a", "b" ] 
number[0]; // undefined 
array.indexOf(undefined); // -1 

如果更改alert行:

alert(odd.indexOf(parseInt(("" + numbers)[0], 10))); 

它應該工作。首先將numbers轉換爲一個字符串,然後獲得0的第十位數字,然後將其轉換回數字。在JSFiddle中,這給我4

+1

轉換numbers[0]整數它不是不確定的,如果我警報號[0]我得到9 – y0ruba

+0

我看到你想要做什麼。將數字投到第一位。 'var number =「1」;數[0]; // 1'或使用'substr' – Halcyon

+0

錯誤的答案與3 upvotes。大多數SO用戶甚至不關心他們看到的是什麼 – letiagoalves

2

number[0]string。在使用indexOf之前,您必須先將其投射出去,以便它可以匹配號碼。

var odd = [1, 3, 5, 7, 9]; 
alert(odd.indexOf(+numbers[0])); 

Working demo

0

數字不具有指標。你可以做的最好的是parseInt((99936).toString()[0]),你的情況可能是9

相關問題