怎么判断两个数组是否相等呢
解决办法
循环数组,一一比较对应位置的每个元素
讨论
因为数组是引用类型,使用=操作符只能对比引用是否指向同一内存空间,如:
var letters:Array = [
"a",
"b",
"c",
"d"];
var lettersPointer:Array = letters;
trace(letters == lettersPointer);
// 显示: true
但是如果数组内容相同,但是在不同的内存空间,=操作就会返回false:
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
另外还可以用ArrayUtilities.equals( ) 方法,该方法需要两个参数:两个数组引用,返回布尔值说明是否相等:
var letters1:Array = [
"a",
"b",
"c",
"d"];
var letters2:Array = [
"a",
"b",
"c",
"d"];
trace(ArrayUtilities.equals(letters1, letters2));
// 显示: true
默认,两个不同排列的数组是不相等的,除非提供第3个参数为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;
}