我试图理解JavaScript数组中获取索引项
的工作原理。
例如,假设我有一个for
循环遍历具有成千上万(或数百万)项的数组。哪种方法(性能最佳)可以打印出这些项呢?
// Option 1
for (int i = 0; i < array.length; i++) {
var data = array[i];
console.log( data.ID, data.name, data.date, data.description );
}
// Option 2
for (int i = 0; i < array.length; i++) {
console.log( array[i].ID, array[i].name, array[i].date, array[i].description );
}
是选项1还是选项2?使用第一个选项或第二个选项是否是同一件事情?或者有更好的方法来做这件事吗?
例如,我知道在Java ArrayList中get()
的工作方式是这样的,因此最好的方法显然是选项1,因为每次调用get()
方法时都会检查范围。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
JavaScript是否以类似的方式工作?
这里的“大问题”实际上是JavaScript数组如何按索引获取元素
注意:我已经尝试搜索获取数组中元素的最佳方法,但我只能找到迭代数组的最佳方法。 这不是我想从这个问题中得到的东西!
console.log
,那么最好的方法是将console.log
应用于整个数组:console.log(array)
,或者console.log(JSON.stringify(array))
。 - hindmost