2012-09-11 6 views
1

j'ai les tableaux suivants de chaînes:comment comparer les deux tableaux de chaînes

array1 = ["a", "b", "c"] 
array2 = ["a", "c", "b"] 
array3 = ["a", "b"] 
array4 = ["a", "b", "c"] 

Comment puis-je comparer les tableaux de telle sorte que:

array1 is array2 #false 
array1 is array3 #false 
array1 is array4 #true 

Répondre

3

Vous ne pouvez pas utiliser le mot-clé is (qui compile à ===), mais vous pouvez ajouter une nouvelle méthode is au prototype de Array:

Array::is = (o) -> 
    return true if this is o 
    return false if this.length isnt o.length 
    for i in [0..this.length] 
    return false if this[i] isnt o[i] 
    true 

Ensuite, utilisez-le comme

array1 = ["a", "b", "c"] 
array2 = ["a", "c", "b"] 
array3 = ["a", "b"] 
array4 = ["a", "b", "c"] 

alert array1.is array2 
alert array1.is array3 
alert array1.is array4