Javascript 循环嵌套变量
Javascript looped nested variable
对这段代码的实际工作方式有点困惑,主要是因为我从未在我的母语中看到这样使用变量 (Python)
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
}
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
我对 list
如何与 for 循环一起使用感到特别困惑。我知道第一次通过时,列表看起来像这样 list = {value: array[i], rest: null};
,但是在 for 循环的第二次通过时,另一个列表如何嵌套在第一个列表中?
list = {}
等同于 list = new Object()
,因此您有时会看到 Javascript 代码像这样即时实例化对象。
这两个示例代表以两种不同方式创建的同一对象。它们并不完全代表您的对象,因为我创建了新数组而不是在 for 循环中显示它们:
//option 1
list = new Object();
list.value = new Array();
list.rest = list;
//option 1
list = {}; //new object
list.value = []; //new array
list.rest = list;
//recall these are each equivalent ways of creating the same object
遍历循环,我发现这是一种递归构造,因为 list 将自身用作 属性。循环从列表末尾的 30 处开始,然后返回到 10。在第一次迭代中,rest: list
引用一个对象(列表),该对象(列表)在 for 循环开始之前设置为 null。这就是为什么在控制台中记录的最后一个值显示为空。然后从右到左读你得到 20,然后是 10。
@Derek 在他的回答中更好地说明了这个过程。
每次调用对象文字时都会创建一个新对象。旧的 list
指针存储在新的 list
中,紧接着将指向新对象的指针存储在 list
变量中。
list = null;
//First iteration
list = {value: 30, rest: null};
│
└────────────────────────┐
//Second iteration │
list = {value: 20, rest: list}; //<-- see this list right here?
// it's being put in before the
// assignment happens.
//so this effectively becomes
list = {value: 20, rest: {value: 30, rest: null}};
//etc.
对这段代码的实际工作方式有点困惑,主要是因为我从未在我的母语中看到这样使用变量 (Python)
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
}
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
我对 list
如何与 for 循环一起使用感到特别困惑。我知道第一次通过时,列表看起来像这样 list = {value: array[i], rest: null};
,但是在 for 循环的第二次通过时,另一个列表如何嵌套在第一个列表中?
list = {}
等同于 list = new Object()
,因此您有时会看到 Javascript 代码像这样即时实例化对象。
这两个示例代表以两种不同方式创建的同一对象。它们并不完全代表您的对象,因为我创建了新数组而不是在 for 循环中显示它们:
//option 1
list = new Object();
list.value = new Array();
list.rest = list;
//option 1
list = {}; //new object
list.value = []; //new array
list.rest = list;
//recall these are each equivalent ways of creating the same object
遍历循环,我发现这是一种递归构造,因为 list 将自身用作 属性。循环从列表末尾的 30 处开始,然后返回到 10。在第一次迭代中,rest: list
引用一个对象(列表),该对象(列表)在 for 循环开始之前设置为 null。这就是为什么在控制台中记录的最后一个值显示为空。然后从右到左读你得到 20,然后是 10。
@Derek 在他的回答中更好地说明了这个过程。
每次调用对象文字时都会创建一个新对象。旧的 list
指针存储在新的 list
中,紧接着将指向新对象的指针存储在 list
变量中。
list = null;
//First iteration
list = {value: 30, rest: null};
│
└────────────────────────┐
//Second iteration │
list = {value: 20, rest: list}; //<-- see this list right here?
// it's being put in before the
// assignment happens.
//so this effectively becomes
list = {value: 20, rest: {value: 30, rest: null}};
//etc.