Javascript 当作为参数传递时,jQuery中的字符串值变得未定义
你好 我正在使用NodeJS和Electron进行一个pet项目。目前它基本上是一个简单的文本编辑器。但是,在保存到文件之前,尝试将文本区域的值传递给函数时遇到了一个问题。 特别是当我调用另一个模块中的函数时,内容的值将变为“未定义”。我怀疑我没有正确地传递它,或者在我进行调用和执行调用之间,它被过度写入,因为字符串应该通过引用传递 渲染器(index.html)的代码如下所示:Javascript 当作为参数传递时,jQuery中的字符串值变得未定义,javascript,jquery,node.js,electron,Javascript,Jquery,Node.js,Electron,你好 我正在使用NodeJS和Electron进行一个pet项目。目前它基本上是一个简单的文本编辑器。但是,在保存到文件之前,尝试将文本区域的值传递给函数时遇到了一个问题。 特别是当我调用另一个模块中的函数时,内容的值将变为“未定义”。我怀疑我没有正确地传递它,或者在我进行调用和执行调用之间,它被过度写入,因为字符串应该通过引用传递 渲染器(index.html)的代码如下所示: let otherModule = require('./js/otherModule.js');
let otherModule = require('./js/otherModule.js');
let $ = require('jquery');
$('#btn_Save').on('click',() => {
// get the fileName, if empty propmt user with save dialog,
//log it to console for debugging
var contents = $('#txt_Content').val();
console.log('with:',contents.substring(0,9),'...');
var finalContents = contents; // (create a copy?)
if(//someConditionMet//)
{
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
//do something with final contents.
})// end of On-click
我已经使用console.log()对函数进行了广泛的评估,并可以确认在调用otherModule之前,内容是正确的,并且与textArea中的内容相匹配。一旦我们在“otherModule”中,事情就会出错
otherModule的代码如下所示:
const someFunc = function(contents, otherVar)
{
console.log('DoThings with:',contents.substring(0,9),'...');
// print shows the value to be undefined...
// do more things
console.log('Did stuff with otherVar:',otherVar.substring(0,9),'...');
// prints just fine as as expected.
// do more things
return someString;
}
module.exports = {
someFunc: someFunc
}
如注释中所述,函数的第一行记录控制台的内容,控制台将子字符串显示为“undefined”
感谢您的时间和考虑
//额外上下文//
我做了一些搜索,但除了知道字符串是通过引用传递的并且是不可变的之外,我还没有看到这样一个问题的答案。有一些关于关闭问题的讨论,但通常是在事件和回调的背景下进行的,我不认为这是本文的背景
//额外信息//
此后,我找到了一个解决方案,使我的参数正确通过。我已经把答案贴在下面了。我做了两件事:
1.将函数定义从“const”更改为“let”
2.更改了参数的顺序,并删除了逗号后的空格。如果您在中获得值,则可以
if(//someConditionMet//)
{
var contents = $('#txt_Content').val(); //New line
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
我已经找到了解决这个问题的办法。我不确定为什么会有不同,但我在“其他模块”中改变了两件事。 1.我将函数从“const”更改为“let” 2.我更改了参数的顺序,删除了逗号后的空格 新的函数头如下所示:
let someFunc = function(otherVar,contents) {...}
我还更新了呼叫以匹配新订单(给定):
我希望这对将来的人有帮助 谢谢你的推荐。然而,当我尝试这是没有效果。我可以验证我是否将值输入到“var contents”中,但当传递给someFunc时,我继续接收未定义的值。
finalContents = otherModule.someFunc(otherVar,contents);