javascript function() 参数问题
阿神
阿神 2017-04-10 17:47:46
[JavaScript讨论组]
function destroyer(arr) {

  var arr1 = Array.prototype.slice.call(arr);
  return arr1;
}

destroyer([1, 2, 3, 1, 2, 3], 20, 30);

现在返回的是[1, 2, 3, 1, 2, 3]这个数组。

问题1:应该怎样修改函数(不修改输入值)能让函数返回[[1, 2, 3, 1, 2, 3], 20, 30]这样的数组?

问题2:Array.prototype.slice.call(),这个方法该怎么理解,怎么用?

阿神
阿神

闭关修行中......

全部回复(5)
巴扎黑

问题一:

function destroyer() {

  var arr1 = Array.prototype.slice.call(arguments);
  return arr1;
}

destroyer([1, 2, 3, 1, 2, 3], 20, 30);

问题二:
根据 es 标准写的,数组的大部分方法被定义为通用的,也就是可以被类数组对象等调用。Array.prototype.slice.call 就相当于在 arguments 这个类数组对象上调用数组的 slice 方法

伊谢尔伦
//我以为不修改输入值是指不能修改参数
function destroyer(arr) {
    var res = [];
    [].forEach.call(arguments,function(e,i){
        res.push(e);
    });
    return res;
}
destroyer([1, 2, 3, 1, 2, 3], 20, 30);
  1. Array.prototype.slice.call()
    建议你了解一下call怎么用;

就如上例代码我写的

[].forEach.call(arguments,function(){});

arguments是类数组对象,forEach是数组的方法,用call就相当于,使得arguments能像数组一样用forEach方法。
同样,slice也是如此~

巴扎黑

function destroyer(arr) {

var arr1 = Array.prototype.slice.call(arr);
return arr1;
}

destroyer([[1, 2, 3, 1, 2, 3], 20, 30]);

转数组用的

高洛峰

1、destroyer([[1, 2, 3, 1, 2, 3], 20, 30]);
2、func.call(obj)就是调用func函数(并把obj作为func里的this),你的例子里就相当于[1, 2, 3, 1, 2, 3].slice()

伊谢尔伦

你传的相当于是三个参数,数组,20,30.你函数只接收1个参数,怎么可能玩的转嘛

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号