javascript - apply传入的数组怎么处理,凌乱了。。。
巴扎黑
巴扎黑 2017-04-11 12:05:29
[JavaScript讨论组]
function test(txt){
    this.key=['red','green','blue']
    this.newArray=txt
    //this.key.push(txt)
}
function test1(){
    test.apply(this,['yellow','orgen'])
}
var fun=new test1()
fun.newArray
=====>"yellow"

传入的是一个数组test里通过txt拿到的却是个字符串"yellow"
但是将apply换成call

function test(txt){
    this.key=['red','green','blue']
    this.newArray=txt
    //this.key.push(txt)
}
function test1(){
    test.call(this,['yellow','orgen'])
}
var fun=new test1()
fun.newArray
=====>["yellow", "orgen"]

得到的却是["yellow", "orgen"]

如果放开this.key.push(txt)在构造函数内部拼接数组最后得到的是["red", "green", "blue", "yellow"](apply换成call也一样)
但是将push放到函数外在实例引用时拼接便能拿到两个数组拼接到一起的情况

function test(txt){
    this.key=['red','green','blue']
    this.newArray=txt
    //this.key.push(txt)
}
function test1(){
    test.call(this,['yellow','orgen'])
}
var fun=new test1()
fun.key.concat(fun.newArray)
=====>["red", "green", "blue", "yellow", "orgen"]

目的在构造函数内部完成数组正确拼接

巴扎黑
巴扎黑

全部回复(2)
迷茫
// call
function test (array) {
  this.key = ['red', 'green', 'blue']
  this.newArray = this.key.concat(array)
}
function test1 () {
  test.call(this, ['yellow', 'orgen'])
}
var fun = new test1()

console.log(fun.newArray)

// apply
function test () {
  this.key = ['red', 'green', 'blue']
  var array = Array.prototype.slice.call(arguments, 0)
  this.newArray = this.key.concat(array)
}
function test1 () {
  test.apply(this, ['yellow', 'orgen'])
}
var fun = new test1()

console.log(fun.newArray)

你是想要这样的效果吗?

伊谢尔伦
function test(txt,str){
    this.key=['red','green','blue']
    this.newArray=[txt,str]
    //this.key.push(txt)
}
function test1(){
    test.apply(this,['yellow','orgen'])
}
var fun=new test1()
//改为这样你对apply应该就能理解了吧
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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