这不适合面试,不用担心:)
我很好奇为什么这两个函数的变化不同:
var redundantSlice1 = function() {
return arguments[0].slice(Array.prototype.slice.call(arguments).slice(1).join())
};
var redundantSlice2 = function() {
return arguments[0].slice(1,2)
};
redundantSlice1([1,2,3], 1, 2) // [1,2,3]
redundantSlice2([1,2,3], 1, 2) // [2]
redundantSlice2
会返回我的预期,但1,2
是硬编码的,这就是我要避免的。
为什么第一个函数的1,2
为undefined
?
答案 0 :(得分:1)
在redundantSlice1
中,.join( )
默认情况下将参数转换为以,
作为分隔符的字符串。所以你的样本,声明
Array.prototype.slice.call( arguments ).slice( 1 ).join( )
实际上"1,2"
不是[ 1, 2 ]
,就像你期望的那样。
除此之外,您只将一个参数传递给.slice( )
。为了匹配redundantSlice2
的行为,您必须使用.apply( )
。
var redundantSlice1 = function() {
var firstArg = arguments[ 0 ];
return Array.prototype.slice.apply(
firstArg,
Array.prototype.slice.call( arguments, 1 )
);
};
答案 1 :(得分:1)
如果你想这样做,你可以传递一个数组或类似数组的对象,并得到相同的结果
id
这将与传入的1,2或3个参数一起使用,就像Array.slice一样工作
如果你坚持切断参数并且没有"形式参数"功能
var redundantSlice1 = function(array, begin, end) {
return Array.prototype.slice.call(array, begin, end)
};