2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript: 組み込み関数が降参する瞬間

Last updated at Posted at 2025-11-03

console上でいわゆるUncaught RangeError: Maximum call stack size exceededなどと宣言されちゃう処理を検証。

deep clone

そんな浅い所で根を上げてしまうとは情けない。

let A=[];
for(let a=3644,B=A;a--;)B=B[0]=[];
structuredClone(A)

平坦化

深度たったの9519か…53め。

let A=[],a=9519;
for(let b=a,B=A;b--;)B=B[0]=[];
A.flat(a)

平坦化+循環参照

平坦化しても要素数0個ですが…とても時間がかかります。終わるのかどうか未確認です。

let A=[],a=32;
for(let b=a,B=A;b--;)B=B[0]=B[1]=[];
A.flat(a)

計算上では平坦化により要素数が233-2(8589934590)になります。Invalid array length宣言が先でしょうか? かなり時間がかかるので未確認です

let A=[],a=32;
for(let b=a,B=A;b--;)B=B[0]=B[1]=[,,b];
A.flat(a)

蛇足

深い階層にも対応したArray.prototype.flatもどきを書いてみます。手抜きですが。

簡易版
function flat(A,copy){
	var B=[],b=0,c;
	for(copy?A=[...A]:0;A.length;c?.pop?A.unshift(...c):B[b++]=c)c=A.shift();
	return B
}
spread構文の限界対応版
function flat(A,copy){
	var B=[],a,b=0,c,d;
	for(copy?A=[...A]:0;a=A.length;){
		c=A.shift();
		if(c?.pop)
			if((d=c.length)>>16){//もっと巨大にしても良い
				for(--a;a;)A[--a+d]=A[a];
				for(;d;)A[--d]=c[d]
			}else A.unshift(...c);
		else B[b++]=c
	}return B
}
使用例
let A=[0,[1],2,3,[4,5,[6,7,[8,9],10],11,12],13];
let B=flat(A,true);//展開元保護
document.write(A,"<hr>",B,"<hr>");
flat(A);//展開元破壊
document.write(A.length)

検証環境

Windows7 Google Chrome 109.0.5414.120

2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?