简体   繁体   English

Javascript entry()不返回任何内容

[英]Javascript entries() not returning anything

I want to get the array elements, with their indexes, I use entries() as below but it does not print out anything, and it does not give any errors. 我想获取数组元素及其索引,如下所示使用entry(),但它不会打印出任何内容,并且不会给出任何错误。

 var array1 = ['a', 'b', 'c']; var iterator1 = array1.entries(); for ([k, v] in iterator1) { console.log(k, v) } 

You should use for of instead of for in 您应该使用for of代替for in

 var array1 = ['a', 'b', 'c']; var iterator1 = array1.entries(); for ([k, v] of iterator1) { console.log(k, v) } 


Another way is to use done property and next method of iterators 另一种方法是使用done属性和iterators next方法

 var array1 = ['a', 'b', 'c']; var iterator1 = array1.entries(); let result = iterator1.next() while (!result.done) { let [k, v] = result.value console.log(k, v) result = iterator1.next() } 

To use index and element of an array, you can use the const [key, value] notation in conjunction with the of keyword, in order to use the iterator. 要使用数组的索引和元素,可以将const [key, value]表示法与of关键字结合使用,以便使用迭代器。

 const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) { console.log(index, element); } // 0 'a' // 1 'b' // 2 'c' 

You could also call next on the iterator directly. 您也可以直接在迭代器上调用next。

 var array1 = ['a', 'b', 'c']; var iterator1 = array1.entries(); console.log(iterator1.next().value); // expected output: Array [0, "a"] console.log(iterator1.next().value); // expected output: Array [1, "b"] 

See also: Mozilla docs - Array.entries() 另请参阅: Mozilla文档-Array.entries()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM