【发布时间】:2023-04-07 11:51:01
【问题描述】:
function highest(){
return makeArray(arguments).sort(function(a,b){
return b - a;
});
}
function makeArray(array){
return Array().slice.call( array );
}
assert(highest(1, 1, 2, 3)[0] == 3, "Get the highest value.");
assert(highest(3, 1, 2, 3, 4, 5)[1] == 4, "Verify the results.");
现在,为什么 Array() 甚至返回有意义的东西,没有 new 运算符?如果在没有 new 的情况下调用,我在 JS 中看到的大多数“类”定义都会返回 undefined:
function User(name) {
this.name = name;
this.jump = function() {
console.log(name + " is jumping!");
}
}
assert(typeof(User("no New")) == 'undefined');
【问题讨论】:
-
与其说是“为什么 .slice() 有效?”作为“为什么
Array()似乎和new Array()做同样的事情?” - 答案可以概括为“因为规范是这样说的”。见What's the difference betweenArray(1)andnew Array(1)?。 -
@nnnnnn - 是的,投票决定关闭为 dup,谢谢。
标签: javascript