【发布时间】:2021-08-15 04:30:25
【问题描述】:
我得到了这个用于移动窗口自定进度阅读实验的代码,其中初始显示是由破折号覆盖的句子字符串(由单词分隔)和区域显示(在 csv 中由"," 分隔的多个单词)当您单击句子时会迭代。参与者在一个区域中花费的时间量记录在输出 csv 中。以下是代码和所需的显示:
var _pj;
function replaceWithdash(Sentence, currentWordNumber) {
const sentenceList = Sentence.split(",")
const sigil = sentenceList.map(s => s.replaceAll(/[^\s]/g, "-"))
if (currentWordNumber !== undefined) {
sigil.splice(currentWordNumber, 1, sentenceList[currentWordNumber])
}
return sigil.join("")
}
function _pj_snippets(container) {
function in_es6(left, right) {
if (((right instanceof Array) || ((typeof right) === "string"))) {
return (right.indexOf(left) > (- 1));
} else {
if (((right instanceof Map) || (right instanceof Set) || (right instanceof WeakMap) || (right instanceof WeakSet))) {
return right.has(left);
} else {
return (left in right);
}
}
}
container["in_es6"] = in_es6;
return container;
}
_pj = {};
_pj_snippets(_pj);
Trials_Display.text = replaceWithdash(Sentence, wordNumber);
keypresses = psychoJS.eventManager.getKeys();
sentenceList = Sentence.split(",");
if ((keypresses.length > 0)) {
if (_pj.in_es6("space", keypresses)) {
thisResponseTime = t;
wordNumber = (wordNumber + 1);
if ((wordNumber < sentenceList.length)) {
if ((wordNumber === 0)) {
timeOfLastResponse = 0;
}
thisExp.addData(("IRI_" + wordNumber.toString()), (thisResponseTime - timeOfLastResponse));
timeOfLastResponse = thisResponseTime;
Trials_Display.text = replaceWithdash(Sentence, wordNumber);
} else {
continueRoutine = false;
}
} else {
if (_pj.in_es6("escape", keypresses)) {
core.quit();
}
}
}
所需的显示:
str = "The dog, ate, the food"
console.log(replaceWithdash(str))
//"--- --- --- --- ----"
console.log(replaceWithdash(str, 0))
//"The dog --- --- ----"
console.log(replaceWithdash(str, 1))
//"--- --- ate --- ----"
console.log(replaceWithdash(str, 2))
// "--- --- --- the food"
虽然这段代码确实成功地显示了破折号之间的空格并逐个区域显示,但我的问题是破折号句子的初始显示。看起来它只显示前两个虚线区域,然后一旦您单击以显示第一个区域中的单词,它将调整以显示第三个区域的虚线。此外,由于某种原因,区域之间似乎存在额外的空间。像这样的:
str = "The dog, ate, the food"
//"--- --- ---"
//"The dog --- --- ----"
//"--- --- ate --- ----"
// "--- --- --- the food"
我认为它如何解释没有索引的初始字符串 (console.log(replaceWithdash(str)) 有问题,但我不确定如何解决这个问题或额外的空格。 除了我自学的内容外,我对 Java 脚本还比较陌生,所以任何帮助都将不胜感激!
【问题讨论】:
-
您的函数期望
sentenceList是一个字符串数组,但它是一个字符串。是否缺少调用split(' ')的内容? -
请提供一个可运行的例子。
-
其实好像需要用
split(',') -
我实际上只是编辑了这篇文章,以显示我拥有的另一行代码:sentenceList = Sentence.split(",");。很抱歉!
-
sentenceList = Sentence.split(",");需要在函数内部,需要把参数改成Sentence
标签: javascript string if-statement logging str-replace