从命名函数返回值

Return Value From A Named Function

本文关键字:返回值 函数 从命      更新时间:2023-10-23

我从头开始学习,并试图了解如何更好地从函数中获取值。请考虑以下示例。

/* Screen Orientation Check */
function screenOrientation () {
    var screenOrientationCheck = ($(window).width() > $(window).height())? 90 : 0;
    console.log(screenOrientationCheck) ;
}
screenOrientation();

上面给出了屏幕方向。

/* Viewport Height Check */
function viewportHeight () {
    var viewportHeightCheck = document.documentElement.clientHeight
    console.log('viewportHeight = '+viewportHeightCheck);
};
viewportHeight();

这将为我提供视口高度。

但现在,如果我喜欢处理这些函数的结果,我不知道如何做到这一点。

if ( viewportHeight() > 600 ) {
    console.log('Hooray!!');
};

例如,这个永远不会着火。

if ( screenOrientation() === 90 ) {
    console.log('Hooray!!');
};

同样地,它也从不着火。

如果我喜欢记录screenOrientationCheckviewportHeightCheck,那就是undefined,因为变量只存在于函数的作用域中。我已经理解了这么多。将return添加到下面的任何一个函数中也不起作用。

/* Viewport Height Check */
function viewportHeight () {
    var viewportHeightCheck = document.documentElement.clientHeight
    console.log('viewportHeight = '+viewportHeightCheck);
    return viewportHeightCheck;
};

我知道这是基本的东西。因此,我很抱歉花了你宝贵的时间来问这个问题。

我试图了解如何使用在函数中创建的值,并在代码中一次又一次地调用这些值,而不是让匿名函数在运行时只执行一次。

如果有人有勇气尽可能详细地回答这个问题,也许最后会有一个记录Hooray!!的例子,那么这将是一个好的结局。

您需要返回值。这是一个正在工作的Jsfidle

function getViewportHeight() {
    var viewportHeightCheck = document.documentElement.clientHeight
    return viewportHeightCheck;
};
if ( getViewportHeight () > 600 ) {
    console.log('Hooray!!');
};

在您的特定情况下,这些函数应该返回一个值,因此每次调用它们时,您都会根据页面维度获得一个值。

/* Screen Orientation Check */
function screenOrientation () {
  return ($(window).width() > $(window).height())? 90 : 0;
}
/* Viewport Height Check */
function viewportHeight () {
  return document.documentElement.clientHeight
};
$('#action').on('click', function() {
  $('#info').html('Screen Orientation: ' + screenOrientation() + '<br>' + 
                  'Viewport Height: ' + viewportHeight());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info"></div>
<p>
  <button id="action">Get Values</button>
</p>