# 比较数组

问题:

var letters:Array = ["a", "b", "c", "d"];
var lettersPointer:Array = letters;
trace(letters == lettersPointer); // 显示: true

var letters1:Array = ["a", "b", "c", "d"];
var letters2:Array = ["a", "b", "c", "d"];
trace(letters1 == letters2]; // 显示: false

var equivalent:Boolean = true;
for(var i:int = 0; i < letters1.length; i++) {
if(letters1[i] != letters2[i]) {
equivalent = false;
break;
}
}
trace(equivalent); // 显示: true

var letters1:Array = ["a", "b", "c", "d"];
var letters2:Array = ["a", "b", "c", "d"];
trace(ArrayUtilities.equals(letters1, letters2));
// 显示: true

var letters1:Array = ["a", "b", "c", "d"];
var letters2:Array = ["b", "a", "d", "c"];
trace(ArrayUtilities.equals(letters1, letters2));
// 显示: false
trace(ArrayUtilities.equals(letters1, letters2, true));
// 显示: true
equals( ) 方法用起来很简单，下面是它的代码：
public static function equals(arrayA:Array,
arrayB:Array,
bNotOrdered:Boolean):Boolean {
// 如果两个数组长度不同
if(arrayA.length != arrayB.length) {
return false;
}
// 创建拷贝，不影响原数组
var arrayACopy:Array = arrayA.concat( );
var arrayBCopy:Array = arrayB.concat( );
// 如果忽略排列顺序
if(bNotOrdered) {
arrayACopy.sort( );
arrayBCopy.sort( );
}
// 循环比较
// 如果不匹配，删除拷贝，返回false
for(var i:int = 0; i < arrayACopy.length; i++) {
if(arrayACopy[i] != arrayBCopy[i]) {
delete arrayACopy;
delete arrayBCopy;
return false;
}
}
// 否则相等，删除数组，返回true
delete arrayACopy;
delete arrayBCopy;
return true;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：比较数组 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)