为什么我的两个常量总是具有相同的高度值?
Why does my two constants always have the same height value?
我有一个生成 100 个 div 的程序(不完整),每个 div 都有 class“bar”,每个都有一个随机的 div.height属性。如果您需要每个条形都有随机高度的视觉效果,想象一下直方图。
我使用常量存储柱列表:
const arrayBars = document.getElementsByClassName('bar');
到目前为止一切都很好。
奇怪的是,当我创建两个新常量(barA 和 barB)并尝试 console.log 它们的高度时,它们总是以相同的高度返回,但事实并非如此。我确定问题不在我的随机 div.height 生成器中,因为它们在我程序的其他部分按预期工作。
我认为问题出在我程序的这一部分:
function insertionSort(unsortedArray) {
let length = unsortedArray.length;
for (let i = 1; i < length; i++) {
const arrayBars = document.getElementsByClassName('bar');
const barA = arrayBars[i].style;
let j = i - 1;
const barB = arrayBars[j + 1].style;
console.log(barA.height, barB.height);
}
}
在使用调试器时,我注意到 barB 的高度变为 barA 的高度的时间点是针对以下行:
const barB = arrayBars[j + 1].style;
我觉得这是一个引用问题,但在上面的行中,我从未将 barB 设置为引用 barA。而且 barB 调用 arrayBars 也不可能是事实吧?
既然如此,为什么barA和barB的高度总是一样的?
您正在呼叫
const barA = arrayBars[i].style;
紧接着,你
let j = i - 1;
const barB = arrayBars[j + 1].style;
// j + 1
// = ( i-1 ) + 1
// = i
// => barB = arrayBars[i] = barA
所以你在向后移动时查询同一个节点两次 -1
然后添加 +1
你错误地处理了指针。
假设 i
为 1。您指向数组中的索引 1。
const barA = arrayBars[i].style;
现在 j
是 0。
let j = i - 1;
但是当您说 j+1
时,您再次指向索引 1。
const barB = arrayBars[j + 1].style;
因此 barA
和 barB
始终相同是绝对正确的,因为在这两种情况下您指向相同的索引。
我有一个生成 100 个 div 的程序(不完整),每个 div 都有 class“bar”,每个都有一个随机的 div.height属性。如果您需要每个条形都有随机高度的视觉效果,想象一下直方图。
我使用常量存储柱列表:
const arrayBars = document.getElementsByClassName('bar');
到目前为止一切都很好。
奇怪的是,当我创建两个新常量(barA 和 barB)并尝试 console.log 它们的高度时,它们总是以相同的高度返回,但事实并非如此。我确定问题不在我的随机 div.height 生成器中,因为它们在我程序的其他部分按预期工作。
我认为问题出在我程序的这一部分:
function insertionSort(unsortedArray) {
let length = unsortedArray.length;
for (let i = 1; i < length; i++) {
const arrayBars = document.getElementsByClassName('bar');
const barA = arrayBars[i].style;
let j = i - 1;
const barB = arrayBars[j + 1].style;
console.log(barA.height, barB.height);
}
}
在使用调试器时,我注意到 barB 的高度变为 barA 的高度的时间点是针对以下行:
const barB = arrayBars[j + 1].style;
我觉得这是一个引用问题,但在上面的行中,我从未将 barB 设置为引用 barA。而且 barB 调用 arrayBars 也不可能是事实吧?
既然如此,为什么barA和barB的高度总是一样的?
您正在呼叫
const barA = arrayBars[i].style;
紧接着,你
let j = i - 1;
const barB = arrayBars[j + 1].style;
// j + 1
// = ( i-1 ) + 1
// = i
// => barB = arrayBars[i] = barA
所以你在向后移动时查询同一个节点两次 -1
然后添加 +1
你错误地处理了指针。
假设 i
为 1。您指向数组中的索引 1。
const barA = arrayBars[i].style;
现在 j
是 0。
let j = i - 1;
但是当您说 j+1
时,您再次指向索引 1。
const barB = arrayBars[j + 1].style;
因此 barA
和 barB
始终相同是绝对正确的,因为在这两种情况下您指向相同的索引。