2016-05-09 6 views
-4

JavaScriptでの練習をしています。しかし、私はエラーが発生します。何が間違っているかを見つけ出すスクリプトは、 "名前"が存在する場合に配列をチェックする必要があります。JavaScriptの配列内の値を見つける

// Array with names 

var names = ["Alex", "Mike", "John"]; 


// Function checks if name exist 

name.checkName = function(name) { 
    return (this[name] >= 0) ? 
    alert(name + " is there!") : 
    alert(name + " is not there!") 
}; 


//Function call 

name.checkName('Alex'); 
+2

あなたの配列は 'names'ですが、あなたは' name.checkName'に割り当てています。それは間違っています。 – ssube

+2

あなたは 'indexOf'と言う必要があります。 –

+1

'name'と' name'の間にも問題があります。 –

答えて

3

"名前"は定義しておらず、 "名前"のみを定義しました。さらに、indexOf()メソッドを使用します。 (未テスト)これを試してみてください:

// Array with names 

var names = ["Alex", "Mike", "John"]; 


// Function checks if name exist 

names.checkName = function(name) { 
    return (this.indexOf(name) >= 0) ? 
    alert(name + " is there!") : 
    alert(name + " is not there!") 
}; 


//Function call 

names.checkName('Alex'); 
0

はこれを試して、私はJSでprofficientませんが、私は、Pythonを知っていて、それがnameがであるかどうかをチェックするためにindexOfを使用することができます同じ考え

var names = ["Alex", "Mike", "John"]; 

    for (i = 0; i < names.length; i++){ 
     if (names[i] = name){ 
      alert(name + " is there") 
     }else{ 
      alert(name + " is not there") 
    } 
} 
0

ですnamesアレイ。 また、checkNameを宣言する必要があります。

var names = ["Alex", "Mike", "John"]; 

var checkName = function(name) { 
    return (names.indexOf(name) > -1) ? 
    alert(name + " is there!") : 
    alert(name + " is not there!") 
}; 

checkName('Alex'); 
関連する問題