JavaScript 数组遍历动态增长问题(V8源码解析)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JavaScript 数组遍历动态增长问题(V8源码解析),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2302字,纯文字阅读大概需要4分钟。
内容图文
![JavaScript 数组遍历动态增长问题(V8源码解析)](/upload/InfoBanner/zyjiaocheng/1317/d3d3aaebff6841d6a2cb56f5d81501db.jpg)
数组 arr 在遍历同时动态增长会发生什么呢
let arr = [1,2]
arr.forEach(item => arr.push(...arr))
console.log(arr)
// 输出: [ 1, 2, 1, 2, 1, 2, 1, 2 ]
并未输出 [1,2] 或 [1,2,1,2...] 无限循环下去
JavaScript引擎:V8源码git地址:https://github.com/v8/v8
vscode打开源码文件夹
![技术分享图片](/upload/getfiles/default/2022/10/27/20221027032652807.jpg)
V8-MASTER/src/builtins-collections-gen.cc
数组的循环遍历由 Goto 与 BIND 搭配完成,Goto(adress) 指跳转的目标adress , BIND(adress) 指对应接受的目的地adress
TF_BUILTIN(MapPrototypeForEach, CollectionsBuiltinsAssembler) {
const char* const kMethodName = "Map.prototype.forEach"; // Array 继承自 MapCollections
......
// Ensure that {callback} is actually callable.
Label callback_not_callable(this, Label::kDeferred);
GotoIf(TaggedIsSmi(callback), &callback_not_callable);
GotoIfNot(IsCallable(CAST(callback)), &callback_not_callable);
TVARIABLE(IntPtrT, var_index, IntPtrConstant(0));
TVARIABLE(OrderedHashMap, var_table,
CAST(LoadObjectField(CAST(receiver), JSMap::kTableOffset)));
Label loop(this, {&var_index, &var_table}), done_loop(this); // 记录了数组的初始信息,后期判断是否遍历结束的标志
Goto(&loop);
BIND(&loop);
{
// 中括号内的依然会执行,只是产生了一个块作用域
// 代码快内部执行完后,会被回收资源
// Transition {table} and {index} if there was any modification to
// the {receiver} while we‘re iterating.
TNode<IntPtrT> index = var_index.value();
TNode<OrderedHashMap> table = var_table.value();
std::tie(table, index) = Transition<OrderedHashMap>(
table, index, [](const TNode<OrderedHashMap>, const TNode<IntPtrT>) {});
// Read the next entry from the {table}, skipping holes.
TNode<Object> entry_key;
TNode<IntPtrT> entry_start_position;
std::tie(entry_key, entry_start_position, index) =
NextSkipHoles<OrderedHashMap>(table, index, &done_loop);
// Load the entry value as well.
TNode<Object> entry_value = LoadFixedArrayElement(
table, entry_start_position,
(OrderedHashMap::HashTableStartIndex() + OrderedHashMap::kValueOffset) *
kTaggedSize);
// Invoke the {callback} passing the {entry_key}, {entry_value} and the
// {receiver}.
Call(context, callback, this_arg, entry_value, entry_key, receiver);
// Continue with the next entry.
var_index = index;
var_table = table;
Goto(&loop);
}
BIND(&done_loop);
args.PopAndReturn(UndefinedConstant());
BIND(&callback_not_callable);
......
}
原文:https://www.cnblogs.com/lhx9527/p/14752681.html
内容总结
以上是互联网集市为您收集整理的JavaScript 数组遍历动态增长问题(V8源码解析)全部内容,希望文章能够帮你解决JavaScript 数组遍历动态增长问题(V8源码解析)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。