簡體   English   中英

有沒有辦法從另一個javascript函數更改函數的參數?

[英]Is there a way to change a function's arguments from another javascript function?

我試圖更改另一個函數內的函數參數,然后將其返回給被調用函數。 我正在嘗試這樣的事情:

function func(a,b,c) {
    console.log(arguments, a, b, c); //[1, true, "a"] 1 true "a"
  arguments[0] = 2;
    console.log(arguments, a, b, c); //[2, true, "a"] 2 true "a"
  arguments = ArgumentsToNumber.apply(this, arguments);
  console.log(arguments, a, b, c); //[2, 1, NaN] 2 true "a"
}

function ArgumentsToNumber() {
    for (let i = 0; i < arguments.length; i++) {
    arguments[i] = Number(arguments[i]);
  }
  return arguments;
}

func(1, true, 'a');

我想更改abc變量。

您必須傳遞Arguments對象本身,而不是在apply中將其用作類似於數組的對象:

function func(a, b, c) {
  console.log(a, b, c); // 1, true, "a"
  arguments[0] = 2;
  console.log(a, b, c); // 2, true, "a"
  argumentsToNumber(arguments);
  console.log(a, b, c); // 2,    1, NaN
}
function argumentsToNumber(args) {
  for (let i = 0; i < args.length; i++)
    args[i] = +args[i];
}
func(1, true, 'a');

請注意,更改另一個函數中的參數會導致性能下降。

暫無
暫無

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

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