说明
For loops contain 3 statements in their body:
for (initialization; condition; final-expression)
我想您了解initialization 和final-expression 的工作原理,但condition 是确定for 循环是继续迭代还是终止的测试。
由于node 在这种情况下可以是对象或null,因此它们是“真实”和“虚假”值。 Boolean(null) === false,所以如果当前迭代已经到达null,它就知道链表已经结束,可以停止循环了。
演练
好的,所以第二个for循环以node = list开头的原因是因为list是一个需要遍历的object。请注意,下一个node 始终包含在node.rest 中。因此,为了“增加”,我们需要使用node = node.rest 将node.rest 分配给node。现在我们了解了这些部分:
for (var node = list; ... ; node = node.rest)
剩下的部分是检查 for 循环是否应该继续或终止的语句。我们知道如果node 是null,那么就没有更多的节点可以遍历了,所以我们可以检查一下。在 JavaScript 中,由于Boolean(null) === false,我们可以简单地断言node 是“真实的”以继续,因为Boolean({}) === true。所以node这个语句只是检查是否继续:
for (var node = list; node; node = node.rest)
演示
在学习语言结构时,最有用的事情之一就是运行代码并亲自查看输出的样子。在此示例中,array 是
["hello", "world", "how", "are", "you", "today"]
list 是
{"value": "hello", "rest": {"value": "world", "rest": {"value": "how", "rest": {"value": "are", "rest": {"value": "you", "rest": {"value": "today", "rest": null}}}}}}
/* ignore this */
console.log = function (data) {
if (typeof data === 'object') {
data = JSON.stringify(data, null, 2);
}
document.write('<pre>' + data + '</pre>');
}
/* pay attention to everything below here */
function arrayToList(array) {
console.log('arrayToList\n\n');
var list = null;
for (var i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
console.log('index: ' + i);
console.log('value: ' + JSON.stringify(array[i]));
console.log(list);
console.log('-----');
}
return list;
}
function listToArray(list) {
console.log('listToArray\n\n');
var array = [];
for (var node = list; node; node = node.rest) {
array.push(node.value);
console.log('index: ' + (array.length - 1));
console.log('value: ' + JSON.stringify(array.slice(-1)[0]));
console.log(node);
console.log('-----');
}
return array;
}
var array = ['hello', 'world', 'how', 'are', 'you', 'today'];
var list = arrayToList(array);
listToArray(list);
pre {
margin: 0;
padding: 0;
}