[英]Javascript how is the const variable being reassigned in this problem?
下面的代码将一个数组作为输入,例如
["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
function 中,每次 function 递归调用自身时, const temp = s[left]
变量都会重新分配给一个新值。 我试图了解它是如何工作的,因为我知道不能重新分配“const”变量。 我的直觉是每次 function 递归调用自身时都会创建一个新的 const temp 变量? 这使您看起来像是在重新分配一个 const 变量,但实际上您每次都在创建一个新变量? 谁能进一步解释一下,谢谢
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 function 中,每次 function 递归调用自身时,const temp = s[left] 变量都会重新分配给一个新值。
不,不会的。 :-) 一个不同的temp
常数,特定于对 function 的其他调用,被分配了新值。 原始调用中存在的temp
常数不变(其性质也是如此)。 对 function 的每次调用都会获得自己的一组本地参数/变量/常量。 (这一事实通常是递归函数正常工作的核心。)
这是一个带有一些日志记录的更简单的示例:
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
的第一次调用¹会创建规范所称的词法环境 object ,其中将包含该 function 调用的所有顶级声明(包括temp
)。 当example
调用自身时,会为第二次调用创建一个新的、单独的词法环境 object。 等等。通常,如果 function 返回并且没有在其中创建闭包,则词法环境及其内容将被丢弃,但在上面我创建函数并将它们存储在fns
中以便我们可以看到这些值,从而保留那些不同的词汇环境(因为函数关闭它们)。
¹“理论上”,因为 JavaScript 引擎可以按照它想要的任何方式实现它,只要它的行为符合规范所说的行为。 虽然他们可能会在词法环境中使用内部 object,但他们也可以避免这种情况,只使用压入堆栈的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.