我被告知不要for...in在JavaScript中使用数组.为什么不?
我知道什么是for... in循环(它迭代密钥),但第一次听到for... of(它迭代值).我对for... of循环感到困惑.我没有得到.这是下面的代码:
var arr = [3, 5, 7];
arr.foo = "hello";
for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (var i of arr) {
console.log(i); // logs "3", "5", "7"
//it is does not log "3", "5", "7","hello"
}
Run Code Online (Sandbox Code Playgroud)
我得到的是,for... of迭代属性值.那么为什么它不记录(返回)"3", "5", "7","hello"而不是"3", "5", "7"?但for... in循环迭代每个键("0","1","2","foo").这里for... in循环也迭代foo密钥.但是对于...不是对foo财产价值的迭代,即"hello"为什么它是这样的?
简而言之:
在这里我控制台 …
.NET 3.5作业的面试问题是"迭代器和枚举器之间有什么区别"?
这是一个核心区别,LINQ等等.
无论如何,有什么区别?我似乎无法在网上找到一个可靠的定义.毫无疑问,我可以找到两个术语的含义,但我得到的答案略有不同.面试的最佳答案是什么?
IMO迭代器"迭代"集合,枚举器提供迭代功能,但必须调用它.
此外,使用yield关键字据说可以保存状态.究竟是什么状态?是否有这种好处的例子?
I am looking for a best way to iterate through NodeList excluding length. I am using:
var foo = document.querySelectorAll('[id^=foo_id]')
console.log(foo)
Run Code Online (Sandbox Code Playgroud)
Returned NodeList has all the required elements + the last entry of length:.
0: input#foo_id_...
1: input#foo_id_...
..................
n: input#foo_id_...
length: n+1
Run Code Online (Sandbox Code Playgroud)
I wonder what the most efficient way to iterate through that NodeList. I can utilize list length etc, but would like to know if there is a more "elegant" way.