簡體   English   中英

Function 從兩個不同的來源接收參數

[英]Function receive parameters from two different sources

我想知道 function 是否可以從兩個不同的來源接收兩個不同的參數。 一個源是事件目標,第二個是在不同的 function 中產生的變量。

document.getElementById("test").addEventListener("click", combine);

function one(numbers){
  //numbers = [1,2,3]
  var test = numbers.push("4")
  combine(test)  
}

function combine (e,test){
  console.log (e.target)
  console.log(test)
}

當我嘗試同時記錄“e”和“test”時,通常一個或另一個返回未定義。

有沒有其他方法可以添加由一個 function 生成的數組和來自事件偵聽器的事件?

假設您在某處將 function 稱為“一”。

var test=numbers.push(4);

這里“test”的值將是“4”而不是“1 2 3 4”

調用“組合”function 時,您必須輸入 2 個參數,否則空參數將返回未定義

代碼應該是這個樣子:

function one(){
  numbers = [1,2,3]
  numebrs.push(4);
  var test = numbers;
  combine(whatever,test)  
}

function combine (e,test){
  console.log (e.target)
  console.log(test)
}

您可以做的是調用combine ,其中 combine function 從one檢索值?

在這種情況下,它會像:

document.getElementById("test").addEventListener("click", combine);

function one(numbers){
  //numbers = [1,2,3]
  var test = numbers.push("4")
  return test;
}

function combine (e){
  let test = one(); //create locally scoped variable 'test' and get value from 'one' function
  console.log (e.target)
  console.log(test)
}

否則,您需要將值存儲在兩個函數都可以訪問的變量中嗎? 下面假設'numbers'參數在別處初始化?

document.getElementById("test").addEventListener("click", combine);

var _test = [];
function one(numbers){
  //numbers = [1,2,3]
  //var test = numbers.push("4")
  //return test;

  numbers.push("4"); //assuming numbers is an array?
  _test = numbers;
}

function combine (e){
  console.log (e.target)
  console.log(_test)  // '_test' in this case is a variable available in overarching scope?
}

看到這個小提琴: https://jsfiddle.net/f4vbpsoe/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM