javascript - apply传入的数组怎么处理,凌乱了。。。
本文介绍了javascript - apply传入的数组怎么处理,凌乱了。。。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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"]
目的在构造函数内部完成数组正确拼接
解决方案
// 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)
你是想要这样的效果吗?
这篇关于javascript - apply传入的数组怎么处理,凌乱了。。。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文