*****编辑为包含 TRUE 最小可重复示例*****
我有一个嵌套的for
循环,该循环从一个数组读取元素并将其写入另一个数组。内部for
循环应该检查其中一个数组中的元素,并在元素不相等时break
返回外部数组。
对于所有相关问题,我都引用了stackoverflow来尝试找到解决方案。我试过将数组元素写入变量并进行比较,但结果是相同的。 if
条件正在异常触发,我无法确定模式是什么。
我一直在测试条件下使用Logger.log
,并设法查明了引起问题的for
语句-但我一直无法找到解决方案。
function importCollection() {
var xpacs = [[1], [1], [1], [1], [1], [1], [2], [2], [3], [3], [3]];
var cards = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]];
var cards0 = [];
var cards1 = [];
var cards2 = [];
var cards3 = [];
var cards4 = [];
var a = 0;
var b = 0;
var c = 0;
var x = 0;
var y = 11;
for (b;c<y;b++) {
x = xpacs[c];
// Logger.log("x: "+x)
// Logger.log("xpacs: "+xpacs[c]);
PACK_LOOP: for (var a=0;a<5;a++) {
if (c==y || x!=xpacs[c]) { // ***** ERROR - This is the code that is triggering too often
Logger.log("Row: "+b);
Logger.log("Col: "+a);
Logger.log("Card: "+c);
Logger.log(x);
Logger.log(xpacs[c]);
Logger.log("This if statement shouldn't be triggering when the two lines above are equal!");
break PACK_LOOP
}
eval("cards"+[a]+"[b] = cards[c]");
c++;
}
}
Logger.log(cards0);
Logger.log(cards1);
Logger.log(cards2);
Logger.log(cards3);
Logger.log(cards4);
}
预期结果应该是:
[[1.0], [6.0], [7.0], [9.0]]
[[2.0], null, [8.0], [10.0]]
[[3.0], null, null, [11.0]]
[[4.0], null, null, null]
[[5.0], null, null, null]
谢谢大家的帮助
答案 0 :(得分:1)
An expression comparing Objects is only true if the operands reference the same Object
数组是一个对象。当您比较两个对象时,它们将始终为假。此时,
if (c==y || x!=xpacs[c])
如果x和xpacs [c]分别为[1.0]
和[1.0]
,由于您正在比较两个对象,
[1.0] === [1.0] //false both objects don't refer the same object in memory
[1.0] !== [1.0] //true both objects don't refer the same object in memory
[1.0][0] === [1.0][0] //true as 1 === 1
您需要比较原始值:(字符串,数字,布尔值):
if (c==y || x[0]!=xpacs[c][0])