我想创建一个在 Javascript 中交换数组的 2 个元素的函数,所以我创建了这段代码:let arrayOne = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];function swapThatFails(element1,element2) { arrayOne[arrayOne.indexOf(element1)] = element2; arrayOne[arrayOne.indexOf(element2)] = element1; console.log("arrayOne = ",arrayOne);}swapThatFails ("elementA", "elementC");但是,它对原始数组没有任何改变。我设法通过获取要交换的数组的索引来使其工作:let arrayTwo = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];function swapThatWorks(element1,element2) { let index1 = arrayTwo.indexOf(element1); let index2 = arrayTwo.indexOf(element2); arrayTwo[index1] = element2; arrayTwo[index2] = element1; console.log("arrayTwo = ",arrayTwo);}swapThatWorks ("elementA", "elementC");对我来说,它们都是相同的,除了第二个是分两步完成的,所以看起来更容易理解。为什么第一个不起作用,而第二个起作用?let arrayOne = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];let arrayTwo = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];function swapThatFails(element1,element2) { arrayOne[arrayOne.indexOf(element1)] = element2; arrayOne[arrayOne.indexOf(element2)] = element1; console.log("arrayOne = ",arrayOne); }function swapThatWorks(element1,element2) { let index1 = arrayTwo.indexOf(element1); let index2 = arrayTwo.indexOf(element2); arrayTwo[index1] = element2; arrayTwo[index2] = element1; console.log("arrayTwo = ",arrayTwo); } swapThatFails ("elementA", "elementC");swapThatWorks ("elementA", "elementC");
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
让我们考虑一下
function swapThatFails(element1,element2) {
arrayOne[arrayOne.indexOf(element1)] = element2;
arrayOne[arrayOne.indexOf(element2)] = element1;
console.log("arrayOne = ",arrayOne);
}
假设数组是['a','b']并且你用swapThatFails('a', 'b').
首先你搜索element1并放在element2那里
arrayOne[arrayOne.indexOf(element1)] = element2;
你的数组变成['b','b']
然后你搜索element2并放在element1那里。但是数组已经被修改了!第一次出现element2的不是原来的位置,而是新的位置,也就是上一步刚刚被替换的位置。
因此这
arrayOne[arrayOne.indexOf(element2)] = element1;
查找b为第一个元素并将其替换为a. 你得到了['a','b']。这不是你所期望的!
另一方面,如果您首先搜索元素,获取正确的索引然后替换元素,它会按预期工作。
添加回答
举报
0/150
提交
取消