2016-11-18 34 views
-4

enter image description hereJavascript - 不能檢查數組中是否有數字

這是一個糟糕的情況。

我想檢查數字是否在給定的數字數組中。 但它返回神祕的結果。

這是我捕獲的控制檯鏡像。

我還檢查數組的類型和元素。 藍色包含數字類型元素,紅色包含字符串類型元素。 對於單個數字,藍色數字是數字類型,黑色數字是字符串類型。 但類型不影響結果的任何內容。

檢查完所有結果後,我找出10以上的數字,兩位數,出現問題。 1〜10個數字不會造成奇怪的情況。

什麼問題?我怎樣才能解決這個問題?


這是我的代碼。 這是長碼的一部分,所以我稍微調整一下以便單獨理解。

object = {'2': obj,'3': obj,'10': obj,'11': obj,...} 

var array = Object.keys(object); 
var newArray = array.map(function(x) { 
    return parseInt(x, 10) 
}); 
var newNumber = parseInt(number, 10) // number is from above code, just a number. 

console.log(newArray); 
console.log(newNumber); 
console.log(newNumber in newArray); 

console.log(array); 
console.log(number.toString()); 
console.log(number.toString() in array); 
    ` 
+6

不能看到你的代碼,所以誰知道你做錯了 –

+0

對不起。我添加了我的代碼。這是長碼的一部分,所以我很難解釋它。如果需要任何其他信息,請讓我知道。 –

+3

你不能使用'in'來檢查數組中的值,你可以使用'indexOf'來換取 – adeneo

回答

0

您可以嘗試Array.indexOf

var array = [2,3,10,11,12,13,14,18,20,21,25]; 
var myObject = {'2': obj,'3': obj,'10': obj,'11': obj} 

for (let key in myObject){ 
    if (array.indexOf(parseInt(key)) == -1){ //If the value is not found 
     //Element not found 
    } 
    else{ 
     //Element found 
    } 
} 

更多信息有關Array.indexOf可以發現here

0

要檢查數組中是否存在元素(true/false),您需要檢查newArray.indexOf(newNumber) !== -1newArray.indexOf(newNumber) > -1如下。

此外,在上面的代碼array.map(function(x) { return parseInt(x, 10) },你沒有附近array.map(

打開支架工作代碼:

var obj = {}; 
 
var object = {'2': obj, '3': obj, '10': obj, '11': obj}; 
 

 
var array = Object.keys(object) 
 
var newArray = array.map(function(x) { 
 
    return parseInt(x, 10) 
 
}); 
 
    
 
var number = 10; 
 
var newNumber = parseInt(number, 10); // number is from above code, just a number. 
 

 
console.log(newArray); 
 
console.log(newNumber); 
 
console.log(newArray.indexOf(newNumber)); 
 
console.log(newArray.indexOf(newNumber) !== -1); // To get true or false you need either this or the below one 
 
console.log(newArray.indexOf(newNumber) > -1);

相關問題