将从javascript函数返回的值赋给变量

时间:2013-02-05 22:48:49

标签: javascript function variables return-value

我有一个返回字符串的函数,我需要多次调用该函数并将结果放在变量中。

我有这个:

function GetValue() {
    ... Do Something ...
    console.log(string); // displays 'string'
    return string;
}

我正在尝试将函数的输出分配给另一个函数中的变量。目前我正在这样做:

var theString = GetValue();
console.log(theString); // displays 'undefined'

我不明白的是,函数中的控制台输出显示的是值,但是在将变量赋值给函数的输出后却没有。

显然,这不是将函数输出赋给变量的方法。那我该怎么做呢?

[其他信息]

显然,我在示例代码中简要介绍的做法只会引起混淆。

这是我需要从javascript文件中的其他地方多次调用的完整函数:

/*
* Build URL link
*/
function BuildUrlTargetFolder() {
    // Get the current url and remove the 'zipCodes/branchAdmin' part of it for the branch url link
    var urlArray = window.location.href.split('/'),
    targetLength = urlArray.length - 3,
    i,
    targetFolder = '';

    for (i = 0; i < targetLength; i++) {
        // Only add a slash after the 'http:' element of the array
        if (i === 0) {
            targetFolder += urlArray[i];
        } else {
            targetFolder += '/' + urlArray[i];
        }
    }

    console.log('targetFolder: ' + targetFolder); // console output is the current url minus two "levels"

    return targetFolder;
}

这是函数需要使用的地方之一:

var targetFolder = BuildUrlTargetFolder();

console.log('targetFolder: ' . targetFolder); // console output: "undefined"

// If the url has a value, set the href attribute for the branch link otherwise hide the url
if (data['url'] !== '') {
    $('a#branchLink').attr('href', targetFolder + '/index.php/coverage-area/' + data['url']).show();
} else {
    $('a#branchLink').attr('href', '#').hide();
}

所以,说过,如何从分配给调用代码变量的函数中获取字符串?

1 个答案:

答案 0 :(得分:3)

问题在于这一行:

console.log('targetFolder: ' . targetFolder); // console output: "undefined"

.应为+

如上所述,您的代码相当于这样做:

console.log('targetFolder'.targetFolder);

换句话说,它计算字符串'targetFolder'的targetFolder属性(强制转换为String实例) - 这是未定义的。

相关问题