将类数组转化成数组
首先说说什么是类数组:
1.拥有length属性,其它属性(索引)为非负整数(对象中的索引会被当做字符串来处理,这里你可以当做是个非负整数串来理解),
2.不具有数组所具有的方法,
比如:arguments
将类似数组的对象转化成真正的数组的方法:
方法一:
var arr = Array.prototype.slice.apply(arguments); 或 var arr = Array.prototype.slice.call(arguments);
<script> var aa = function(a, b, c, d){ var arr1 = Array.prototype.slice.apply(arguments); var arr2 = Array.prototype.slice.apply(arguments); console.log(arguments instanceof Array); //false console.log(arr1); //[1, 2, 3, [1, 2, 3]] console.log(arr1 instanceof Array); //true console.log(arr2); //[1, 2, 3, [1, 2, 3]] console.log(arr2 instanceof Array); //true }; aa(1,2,3,[1,2,3]); </script>
方法二:
var kong = [];
var arr = Array.prototype.concat.apply(kong, arguments);
注意这种方式的特点和其他的区别
<script> var aa = function(a, b, c, d){ var kong = []; var arr1 = Array.prototype.concat.apply(kong, arguments); console.log(arguments instanceof Array); //false console.log(arr1); //[1, 2, 3, 1, 2, 3] console.log(arr1 instanceof Array); //true }; aa(1,2,3,[1,2,3]); </script>
方法三:
var kong = [];
var arr = Array.apply(kong, arguments);
<script> var aa = function(a, b, c, d){ var kong = []; var arr = Array.apply(kong, arguments); console.log(arguments instanceof Array); //false console.log(arr); //[1, 2, 3, [1, 2, 3]] console.log(arr instanceof Array); //true }; aa(1,2,3,[1,2,3]); </script>
方法四:
比较好理解的便是for循环了。
<script> var aa = function(a, b, c, d){ var arr = [], i = 0, len = arguments.length; for(; i < len; i++){ arr[i] = arguments[i]; } console.log(arguments instanceof Array); //false console.log(arr); //[1, 2, 3, [1, 2, 3]] console.log(arr instanceof Array); //true }; aa(1,2,3,[1,2,3]); </script>
方法五:
var arr = Array.from(arguments); 这是ES6新增加的方法
<script> var aa = function(a, b, c, d){ var arr = Array.from(arguments); console.log(arguments instanceof Array); //false console.log(arr); //[1, 2, 3, [1, 2, 3]] console.log(arr instanceof Array); //true }; aa(1,2,3,[1,2,3]); </script>
方法六:
var arr = [...arguments]; 这也是ES6新增的扩展运算符
<script> var aa = function(a, b, c, d){ var arr = [...arguments]; console.log(arguments instanceof Array); //false console.log(arr); //[1, 2, 3, [1, 2, 3]] console.log(arr instanceof Array); //true }; aa(1,2,3,[1,2,3]); </script>