ES5/ES6将类数组 转化为 数组

博客主要介绍了将类数组转化为数组的多种方法,包括使用 Array.prototype.slice.call 或 apply、[].slice.call、Function.prototype.call.bind(Array.prototype.slice)、[].concat.apply 等,还提及了 ES6 中使用 Array.from 进行转化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把类数组转化为数组

  • 类数组转化为数组1 : Array.prototype.slice.call(arguments) || Array.prototype.slice.apply(arguments)
//从索引开始出提取数组
var test = function() {
	return Array.prototype.slice.call(arguments) ; //es5
}
let a = test(1,2,3,4)
console.log(a) // [1, 2, 3, 4]

//例二:
var test = function() {
	return Array.prototype.slice.apply(arguments) ; //es5
}
let a = test(1,2,3,4)
console.log(a) // [1, 2, 3, 4]

  • 类数组转化为数组2 : [].slice.call(arguments)
var test = function() {
	return [].slice.call(arguments) ; //es5
}
let a = test(1,2,3,4)
console.log(a) // [1, 2, 3, 4]

  • 类数组转化为数组3:Function.prototype.call.bind(Array.prototype.slice)
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

function test() {
  return slice(arguments);
}

var a = test(1, 2, 3,4); 
console.log(a)// [1, 2, 3, 4]
  • 类数组转化为数组4:[].concat.apply([],arguments)
var test = function(){
  return [].concat.apply([],arguments)
}

var a = test(1,2,3,4); 
console.log(a) //[1,2,3,4]
  • ES6类数组转化为数组 Array.from(arr)
var test = function(){
	return Array.from(arguments)
}
var a = test(1,2,3,4) ;
console.log(a) //[1,2,3,4]


function combine(){ 
    let arr = [].concat.apply([], arguments);  //没有去重复的新数组 
    return Array.from(new Set(arr));
} 

var m = [1, 2, 2], n = [2,3,3]; 
console.log(combine(m,n)); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值