简体   繁体   English

Javascript 如何定义此函数中的参数

[英]How does Javascript define the arguments in this function

I am very new to Javascript and I am trying to figure out how array iteration works.我对 Javascript 很陌生,我想弄清楚数组迭代是如何工作的。 In this code below, could somebody please explain to me how Javascript understands what the arguments in the function relate to -namely: value, index,array.在下面的这段代码中,有人可以向我解释一下 Javascript 如何理解函数中的参数与什么相关——即:值、索引、数组。 Are these reserved keywords.这些是保留关键字。 If 'value', swapped positions inside the parantheses with 'index' would the function still work?如果“值”,用“索引”交换括号内的位置,该函数是否仍然有效? Maybe i'm asking how or where have these arguments been defined?也许我在问这些论点是如何或在哪里定义的?

    var txt ="";
    var numbers =[45,4,56,8, 32];
    numbers.foreach(myFunction);

    function myFunction (value,index,array) {
    txt= txt + value + "<br>";
    }

You can define your function parameters in Two Ways您可以通过两种方式定义函数参数

  1. Positional位置的

In positional it does not matter what is the name of your parameters because parameters are assigned by their position not by their name so you can change myFunction(value, index, array) to myFunction(a, b, c) and It still works because their positions matters not their name.在位置中,参数的名称是什么并不重要,因为参数是按位置而不是名称分配的,因此您可以将myFunction(value, index, array)更改为myFunction(a, b, c)并且它仍然有效,因为他们的职位与他们的名字无关。

  1. Named命名

There is another way to defined function parameters where the position does not matter but naming them does.还有另一种定义函数参数的方法,其中位置无关紧要,但命名它们无关紧要。

For example a subtract function can be defined in two ways例如,可以通过两种方式定义减法函数

function subtract({ firstNumber, secondNumber } = {}) {
  return firstNumber - secondNumber;
} 

which is Named and can be called with both subtract({ firstNumber: 10, secondNumber: 5 }) and subtract({ secondNumber: 5, firstNumber: 10 }) and still both results are the same but you have to remember the names.这是Named并且可以同时使用subtract({ firstNumber: 10, secondNumber: 5 })subtract({ secondNumber: 5, firstNumber: 10 })调用,并且两个结果仍然相同,但您必须记住名称。

But if defined in Positional :但如果在Positional 中定义:

function subtract(firstNumber, secondNumber) {
  return firstNumber - secondNumber;
} 

The two subtract(5, 10) and subtract(10, 5) yields different results because their position matters.两个subtract(5, 10)subtract(10, 5)产生不同的结果,因为它们的位置很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM