我讀了很多關於傳遞一個數組作爲不同返回值的函數參數。但如果我有三個js文件,它就不起作用。JavaScript:如何處理數組作爲函數參數?
main.js
module.exports = function(){
this.deliver = require('./file1.js');
this.start = require('./file2.js');
}
file1.js
module.exports = function(id){
require('./main.js')();
function deliver(id){
console.log('Does deliver() work?:'+id);
var arr = new Array(2);
arr[0] = 'content 1';
arr[1] = 'content 2';
return arr;
}
}
file2.js
require('./main.js')();
start.apply(null, deliver('yes'));
function start(x, y){
console.log('x: '+x);
console.log('y: '+y);
}
你有一個想法,爲什麼交付沒有定義?
@何塞,謝謝。是的,這是整個代碼。如果一切都在一個文件中,它是否工作。但不是在三個文件...
@Quentin,謝謝。你有一個想法,我怎樣才能使它與三個文件的工作? - >我試圖將一個任務從file2外包給file1,因爲我也需要它來執行其他任務。最後,我需要將file1的結果返回到file2中來處理它。在我的例子中,我省略了外包。
感謝您的提示,Qentin。我已經更新了上面的代碼。 deliver(x)現在包含一個參數,我想回到file2.js中。它已經到達file1但不會回來。
我仍在試圖尋找解決方案。我已經理解如何將數據從file2傳遞到file1(反之亦然)。
main.js
module.exports = function(){
this.file1 = require('./file1.js');
this.file2 = require('./file2.js');
}
file1.js
require('./main.js')();
//file2.receive('yes', 'content 1');
module.exports = {
deliver : function(id){
console.log('Does deliver() work?:'+id);
return file2.receive(id, 'content 1');
}
}
file2.js
require('./main.js')();
file1.deliver('yes');
module.exports = {
receive : function(x, y){
console.log('x: '+x);
console.log('y: '+y);
}
}
我就可以開始文件2和數據傳遞到file1如果「返回file2.receive( id,'content 1');「已淡出。我也可以從file1開始,並將數據傳遞給file2,只要「file1.deliver('yes');」已淡出。爲什麼不同時工作?
是file2.js的整個代碼? –
「順便說一下,下面的內容不起作用」 - 當然不會。 '交付'仍然超出了範圍。 – Quentin
是的,我的錯。我的編碼技能很慢,即使理解你的觀點。 – NewbieXXL