JS之类数组的常用操作

154 阅读2分钟

这是我参与更文挑战的第27天,活动详情查看: 更文挑战

类数组的常用操作

遍历参数操作

可以在函数内部直接获取arguments这个类数组的值,也可以对参数进行一些操作

比如对参数进行求和操作

function add(){
	var sum = 0;
	len = arguments.length;
	for(var i = 0;i < len;i++){
		sum += arguments[i];
	}
	return sum;
}
add() //0
add(1,2,3,4) //10	

这意味着可以在函数内部对参数进行一些操作而用以达到预期的效果。

定义链接字符串函数

我们可以通过arguments这个例子定义一个函数来链接字符串。

function myConcat(sep){
	var args = Array.prototype.slice.call(arguments,1)//返回除了第一个参数后面参数生成的数组
	return args.join(sep)//第一个参数用作分隔符号来合并
}
myConcat(" ", "A", "B", "C");
// "A B C"
myConcat("; ", "A", "B", "C");
// "A; B; C"

Array.prototype.slice.call(arguments)能够将具有length属性的arguments转换为数组, 我们可以理解为就是 arguments.toArray().slice() 参考

这段代码说明了,你可以传递任意数量的参数到该函数,并使用每个参数作为列表中的项创建列表进行拼接。日常编码也可以采用这样的方式,把要解决的一类问题抽象成通用的方法用来提高代码的复用性。

传递参数使用

你可以使用apply的方法,让一个函数将自己的arguments传递给另一个函数来使用

function A(){
	B.apply(this,arguments) //B要借用A的参数
}
function B(a,b,c){
	console.log(a,b,c)
}
A(1,2,3) //1 2 3

可以看到A并没有console.log,实际上是把A的参数传递给了B,这样就实现了B借用A参数的效果。

将类数组转换成数组
  • 类数组借用数组方法转数组

    类数组因为不是真正的数组,没有数组类型上自带的那些方法,所以需要用到apply和call方法来借用数组的方法。比如说数组的push方法。

    var arrayLike = { 
      0: 'java',
      1: 'script',
      length: 2
    } 
    Array.prototype.push.call(arrayLike, 'A', 'Q'); 
    console.log(typeof arrayLike); // 'object'
    console.log(Object.prototype.toString.call(arrayLike))//[object Object]
    console.log(arrayLike);
    // {0: "java", 1: "script", 2: "A", 3: "Q", length: 4}
    

    可以看到使用数组的方法成功了,可以看到他只是一个普通的对象类型,本身不会有push方法,这个地方是用的Array原型链上的push方法,可以实现用于类数组的push方法,从而给类数组添加新的元素。

    怎么从arguments转换成数组呢。我们只需要用能返回数组的数组原型链上的方法就行了。

    function sum(a, b) {
      let args = Array.prototype.slice.call(arguments);
     // let args = [].slice.call(arguments); // 这样写也是一样效果
      console.log(args.reduce((sum, cur) => sum + cur));
    }
    sum(1, 2);  // 3
    function sum(a, b) {
      let args = Array.prototype.concat.apply([], arguments);
      console.log(args.reduce((sum, cur) => sum + cur));
    }
    sum(1, 2);  // 3
    

    可以看到有两种方法。Array.prototype.slice.call(arguments)Array.prototype.concat.apply([], arguments)都可以办到,返回的数组也都可以成功使用数组的方法reduce。

  • ES6方法转数组

    Array.from方法和...展开运算符

    function sum(a, b) {
      let args = Array.from(arguments);
      console.log(args.reduce((sum, cur) => sum + cur));
    }
    sum(1, 2);    // 3
    function sum(a, b) {
      let args = [...arguments];
      console.log(args.reduce((sum, cur) => sum + cur));
    }
    sum(1, 2);    // 3
    function sum(...args) {
      console.log(args.reduce((sum, cur) => sum + cur));
    }
    sum(1, 2);    // 3