我简单易懂的解释是这样的。我有两个数组,FilterList
和GamesReset
。每当我使用此功能并通过复选框和下拉菜单过滤掉某些游戏时,该功能便会以FilterList=GamesReset;
之类的内容开始。这个功能似乎工作得很好,直到我过滤掉游戏的年龄。该函数从不接触GamesReset
,除非它是while(i<GamesReset.length){}
或FilterList=GamesReset;
之类的东西。我在筛选游戏时使用的唯一工具是FilterList.splice(i,1);
。现在,GamesReset
肯定,应该永远不会改变,据我所知。我让它重置FilterList
,然后根据需要过滤的内容,它将开始从FilterList
中删除这些游戏。我的问题是,GamesReset
也被过滤了。这完全说不通啊。就像我的标题,就像写b=0;
a=b;
a++;
,现在b
等于1。
GamesReset
发生了什么,GamesReset
数组(使用<br>
来分隔每个数组),当我只在JavaScript中更改FilterList
时,它就会发生变化。如果您查看页面源代码,实际代码可能与我上面提到的稍微不同,但它几乎是100%相同的东西。我也想有代码可用,没有url和在这个页面上,但我不知道如何做到这一点与html标签包括。
实际上,这是JavaScript函数。当我的问题被拒绝时,我才明白4个空格的事。
function SearchFilter() {
Games = GamesReset;
plat = document.getElementById('platformcheck').checked;
rpg = document.getElementById('rpgcheck').checked;
puzz = document.getElementById('puzzlecheck').checked;
hybo = document.getElementById('hybocollectcheck').checked;
ages = document.getElementById('agescheck').value;
if ((!plat) && (!rpg) && (!puzz) && (!hybo)) {
FilterList = Games;
} else {
FilterList = [];
i = 0;
while (i < Games.length) {
Set = '';
Set = Games[i];
Set = Set.split('</>');
StrFind = Set[0];
if (
(plat && (StrFind.search(',platform,') > -1)) || (rpg && (StrFind.search(',rpg,') > -1)) || (puzz && (StrFind.search(',puzzle,') > -1)) || (hybo && (StrFind.search(',hybocollect,') > -1))) {
FilterList.push(Games[i]);
}
i++;
}
// so by now, we should have the filtered array
}
//seperate filter for ages
i = 0;
while (i < FilterList.length) { //The problem should definitely start here
Set = '';
Set = FilterList[i];
Set = Set.split('</>');
StrFind = Set[1];
if ((Math.abs(StrFind)) > ages) {
FilterList.splice(i, 1);
} else {
i++;
}
}
GL.innerHTML = GamesReset.join('<br>');
}
提醒一下,当年龄过滤器工作时,问题就开始了。它唯一做的就是FilterList.splice(i,1);
。但它最终改变了GamesReset
。当我添加Games=GamesReset;
时,我稍微改变了这个函数,但这是另一个测试,试图确保GamesReset
不会像FilterList
一样被过滤,但它仍然存在。
编辑:我删除了我的url,因为答案肯定解释了一切,所以现在没有必要。
数组在赋值时不会被复制,两个变量将引用相同的数据。在JavaScript中按值复制数组
这很有意义,因为变量只是对内存中对象的引用。一个对象可以有多个引用。想想看:
var a = { foo: 'bar' };
var b = a;
// b is now a reference to a and they both point to the same object
b.foo = 'doe';
alert( a.foo ); // alerts doe
数组也是如此。所以当你做FilterList = GamesReset
你不是复制数组-你只是分配相同的数组给另一个变量。对任何引用所做的任何突变或更改都将反映在所有引用中。
创建一个数组的副本,可以使用slice
:
FilterList = GamesReset.slice();