gpt4 book ai didi

javascript - 重构代码——变量作用域

转载 作者:行者123 更新时间:2023-11-28 00:10:19 25 4
gpt4 key购买 nike

我有 3 个按钮以不同的方式连接输入文本:

 var myTxtArea = document.getElementById('KWarea');
myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');
var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
$('#produce').click(function () {
var endString = "";

myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');
var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
for (var i = 0; i < lines.length; ++i) {
endString += '"*' + $.trim(lines[i]) + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
// console.log(lines[i]);
}
var trimmedStr = endString.slice(0, -1);
$('#result1').html("ctx.keywords MATCHES (" + trimmedStr + ")");
$('#Strlength').html('Total string length: ' + trimmedStr.length);

});

$('#produce2').click(function () {
var endString = "";
for (var i = 0; i < lines.length; ++i) {
endString += '"*' + $.trim(lines[i]) + '*"' + ',';
}
var trimmedStr = endString.slice(0, -1);
$('#result1').html("ctx.keywords MATCHES (" + trimmedStr + ")");
$('#Strlength').html('Total string length: ' + trimmedStr.length);

});

$('#produce3').click(function () {
var endString = "";
for (var i = 0; i < lines.length; ++i) {
endString += '"' + $.trim(lines[i]) + '"' + ',';
}
var trimmedStr = endString.slice(0, -1);
$('#result1').html("ctx.keywords MATCHES (" + trimmedStr + ")");
$('#Strlength').html('Total string length: ' + trimmedStr.length);

});

我想避免一遍又一遍地重复以下内容:

  $('#result1').html("ctx.keywords MATCHES (" + trimmedStr + ")");
$('#Strlength').html('Total string length: ' + trimmedStr.length);

但是 trimmedStr 取决于 endString 并且我无法重构而不最终导致一些 var undefined

Jsfiddle here

非常感谢

最佳答案

看起来更大的重构可能会有所帮助。类似的事情吗?

function getInput () {
var lines = $('#KWarea').val().split('\n');
var plainKeywords = lines.map(function (line) {
// Match the line for correct input string
return line.match(/^\s*\**([a-z 0-9]+)\**\s*$/i)[1];
}).filter(function (word) {
// No match -> discard line
return word !== undefined;
});
return plainKeywords;
}

function getKeywords (type, word) {
if(type == 1) return ['"*' + word + '*"', '"* ' + word + ' *"'];
if(type == 2) return ['"*' + word + '*"'];
return ['"' + word + '"'];
}

function showKeywords (type) {
// Comma seperated list of keywords
var output = getInput().reduce(function (memo, i) {
return memo.concat(getKeywords(type, i));
}, []).join(',');
$('#result1').html('ctx.keywords MATCHES (' + output + ')');
$('#Strlength').html('Total string length: ' + output.length);
}

$('#produce').click(showKeywords.bind(null, 1));
$('#produce2').click(showKeywords.bind(null, 2));
$('#produce3').click(showKeywords.bind(null, 3));

http://jsfiddle.net/g8rsxmy3/5/

关于javascript - 重构代码——变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30955923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com