Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

javascript中,Array在函数内外调用的区别是什么呢?

function iner() {
    let a = Array.call(this, arguments);
    console.log(a);
}
iner(3);

let b = Array.call(this, 3);

像代码中这样,打印的结果如下
image
这是为什么呢,this不都是window吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

没区别,之所以代码示例中ab值不一样,使用因为Array构造函数对实参处理比较坑:

new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength) // arrayLength 一个范围在 0 到 2^32-1 之间的整数

所以问题中代码示例可以视为:

function iner() {
    // element0为arguments对象的数组,即长度为1
    let a = new Array(arguments);
    console.log(a);
}
iner(3);

// 长度为3的稀疏数组
let b = new Array(3);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...