Javascript在这个问题中如何重新分配const变量



下面的代码将采用一个数组作为输入,例如

["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]

并返回

[ 'b', 'l', 'u', 'e', ' ', 'i', 's', ' ', 's', 'k', 'y', ' ', 't', 'h', 'e']

reverseWord函数中,每次函数递归调用自身时,const temp = s[left]变量都会被重新分配给一个新值。我正试图理解这是如何运作的,因为我知道;const";无法重新分配变量。我的直觉是,每次函数递归调用自己时,都会生成一个新的const-temp变量?这让你看起来像是在重新分配一个常量变量,但实际上你每次都在创建一个新变量?有人能进一步解释一下吗,谢谢

var reverseWords = function(s) {
// reverse the entire array
s.reverse();
// function to find the end word inside the array, this is a word that you need to reverse
const findEndWord = (ind) => s[ind] === ' ' || ind === s.length ? ind : findEndWord(ind + 1);
const reverseWord = (left, right) => {
if(left >= right) return;
const temp = s[left];
s[left] = s[right];
s[right] = temp;
reverseWord(left + 1, right -1);
}
// the whole logic using the functions above to find the word in the array 
// and the other function to actually reverse the word in the array
// this logic will find the end word in the array and then reverse the word,
// lastly it will increment the index to the right spot to find the next word.
let index = 0;
while(index < s.length) {
const end = findEndWord(index);
reverseWord(index, end - 1)
index = end + 1;
}
return s;
};
console.log(reverseWords(s));

在reverseWord函数中,每次函数递归调用自身时,const temp=s[left]变量都会被重新分配给一个新值。

不,不会。:-(一个不同的temp常量,特定于该函数的另一个调用,将被分配新值。存在于原始调用中的temp常量保持不变(其性质也是如此(。对函数的每个调用都有自己的一组局部参数/变量/常量。(这一事实通常是递归函数正确工作的核心。(

下面是一个更简单的日志记录示例:

function example(x, fns) {
// Double the parameter's value and store it in a constant
const temp = x * 2;
// Push a function into `fns` that will show *this call's* `x` and `temp` values
fns.push(() => console.log(`x = ${x}, temp = ${temp}`));
// Potentially recurse
if (x - 1 > 0) {
example(x - 1, fns);
}
}
// Call the example function, passing in an array that it
// will push functions to
const fns = [];
example(5, fns);
// Call the functions, which show us the different variables/etc. in each call
for (const fn of fns) {
fn();
}

在该示例中,对example的第一次调用理论上会创建规范所称的词法环境对象,该对象将包含该函数调用的所有顶级声明(包括temp(。当example调用自己时,会为第二次调用创建一个新的、独立的词法环境对象。等等。通常,如果一个函数返回,并且其中没有创建闭包,那么词法环境及其内容将被丢弃,但在上面的例子中,我正在创建函数并将它们存储在fns中,这样我们就可以看到这些值,这使那些不同的词法环境保持活力(因为函数在它们之上闭合(。


;理论上";因为JavaScript引擎可以按照规范所说的方式来实现它。虽然他们可能会在词法环境中使用内部对象,但他们也可以避免它,只使用堆栈上推送的值。

最新更新