问题描述
这本书说:
要在列表上运行(在listToArray和nth中),可以使用像这样的for循环规范:
To run over a list (in listToArray and nth), a for loop specification like this can be used:
for (var node = list; node; node = node.rest) {}
循环的每次迭代,节点都指向当前子列表,并且正文可以读取其value属性以获取当前元素。在迭代结束时,节点移动到下一个子列表。当它为null时,我们已经到达列表的末尾并且循环结束。
Every iteration of the loop, node points to the current sublist, and the body can read its value property to get the current element. At the end of an iteration, node moves to the next sublist. When that is null, we have reached the end of the list and the loop is finished.
问题1 :你能解释一下条件如何for循环有效吗?我知道它正在检查节点(当前列表)是否为空..但节点参数本身如何工作?
Question 1: Could you explain how the condition of the for loop works? I understand that it is checking whether the node(the current list) is null.. but how does the "node" argument by itself work?
问题2 :为什么以下代码不起作用?
Question 2: why doesnt the following code work?
function listToArray(list){
var result = [];
while(list.value != null){
result.push(list.value);
list = list.rest;
}
return result;
};
console.log(listToArray(list));
推荐答案
要了解其工作原理,您需要了解两个事情:
To understand how this works, you need to know two things:
- java脚本如何循环工作。
- 什么是值。
- How java script For loop works.
- What are truthy values.
for循环语句的语法
:
[condition]在每次循环迭代之前要计算的表达式。
如果此表达式的计算结果为true,则执行语句。如果
表达式的计算结果为false,则执行将跳转到for构造后的第一个表达式
。
[condition] An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. If the expression evaluates to false, execution skips to the first expression following the for construct.
In在布尔上下文中计算时,Java脚本, truthy
值的计算结果为true。
In Java script, a truthy
value evaluates to true when evaluated in a Boolean context.
所以,直到节点
一次 null
,我们 说节点
是 truthy
并且评估为true。
So till node
is null
at one point, we may say that node
is truthy
and evaluates to true.
当语句时, node = node.rest
将 null
值分配给 node
,for循环退出。
When the statement, node = node.rest
assigns a null
value to node
, there the for loop exits.
以下代码不起作用,因为 list.value
可能 undefined
,或任何其他 falsy
值的事实她比 null
。
The below code does not work because, list.value
may be undefined
, or as a fact any other falsy
value other than null
.
function listToArray(list){
var result = [];
while(list.value != null){
result.push(list.value);
list = list.rest;
}
return result;
};
console.log(listToArray(list));
改为尝试, while(list.value)
。
这篇关于listToArray雄辩的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!