这两个函数之间的区别是什么;有什么作用?

问题描述 投票:-3回答:1

一个有一个名字,但另一个没有。1功能SwapRedGreenrw()2功能swapGreenRed(pixelh)

如果在括号中写出这样的名称,这意味着什么,因为该功能已经有一个名称。但这即使括号之间没有名称也可以使用。

这里是带图片的编辑Online Editor with the picture]


var img = new SimpleImage("eastereggs.jpg");
img.setSize(170, 170);
print(img);

var pix = img.getPixel(1, 1); // added this code to check the pixel values before processing
print(pix); //print the pixel value for pixel at 1,1

for (var pixels of img.values()) {
  SwapRedGreenrw();
}
// here function number one without name just" SwapRedGreenrw() "
function SwapRedGreenrw() {
  var cR = pixels.getRed();
  var cG = pixels.getGreen();
  var t1 = pixels.setRed(cG);
  var t2 = pixels.setGreen(cR);
}

print(img);
var pix2 = img.getPixel(1, 1); // added this code to check the pixel value after processing
print(pix2);
print("--____________________________________________________________________________");

var imga = new SimpleImage("eastereggs.jpg");
imga.setSize(170, 170);

//here the function number 2 with a name(pixelh) brackets
function swapGreenRed(pixelh) {
  var x = pixelh.getGreen();
  pixelh.setGreen(pixelh.getRed());
  pixelh.setRed(x);
}

for (var pixel of imga.values()) {
  swapGreenRed(pixel);
}
print(imga);

var pix2 = imga.getPixel(1, 1); // added this code to check the pixel value after processing
print(pix2);
print("-- 
    //__________________________________________________________________________________________________");
javascript
1个回答
0
投票

区别是“参数”。

function swapGreenRed(pixelh)
{
var x = pixelh.getGreen();
...

pixelh是传递到函数swapGreenRed中的参数。请注意,稍后调用该行时,该行是

swapGreenRed(pixel);

您可以传入任何存在且类型正确的内容。

如果未指定参数,则必须确保所访问的变量确实存在:

function SwapRedGreenrw()
{
var cR=pixels.getRed();
...

您必须确保pixels存在。而且仅适用于像素。

[注意,在上一个中,它被称为pixel,而不是pixels?正确类型的ANY变量将起作用。

因此,第一种方法是正确的方法:使用参数,以便您可以将函数重用于其他用途,而不是为每次使用编写新的函数。记住DRY:不要重复自己。

© www.soinside.com 2019 - 2024. All rights reserved.