我发现了大量文章讨论数组中字符串的查找/替换方法,但是它们似乎都依赖于“静态字符串”输入进行替换
即:
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red");
我需要查找并替换针对输入事件的检查
var whichKey = (String.fromCharCode(event.keyCode));
还可以动态查找并替换与其他字符串匹配的字符。
请注意:
我正在制作“ hang子手”游戏
用户按“ W”(例如)作为“猜测”:
secretPuzzleSolution = ['s', 'o', 'l', 'u', 't', 'i', 'o', 'n']
puzzleUserSees = ['_', '_', '_', '_', '_', '_', '_', '_']
W不在拼图中,因此他们将失去“尝试” 如果他们按“ S”,则代码将在secretPuzzleSolution []中检查是否为“ s”,并在正确的位置将puzzleUserSees []中的所有“ _”替换为“ s”,并返回新的puzzleUserSees = ['S','_' ,“ _”,“ _”,“ _”,“ _”,“ _”,“ _”,]。
代码成功地在secretPuzzleSolution []中找到了按键,但到目前为止我还无法获得
从secretPuzzleSolution []复制位置,以便将puzzleUserSees []元素更改为正确的位置
替换所有按键实例,而不仅仅是第一个实例(如果secretPuzzleSolution []中有's'的两个元素,请在puzzleUserSees []中的正确位置都进行更改)
到目前为止,它确实可以部分完成这项工作,但是如您所见,它在很多方面都明显被打破了。有什么想法吗?
这是我正在处理的部分:
document.onkeydown = function(e) {
var whichKey = (String.fromCharCode(event.keyCode));
var keyPress = whichKey.toLocaleLowerCase();
var found = secretPuzzleSolution.find(function(element) {
var isMatch = secretPuzzleSolution.indexOf(element);
if (typeof(element) !== 'undefined') {
puzzleUserSees.splice((isMatch), (isMatch), element);
remainingMystery--;
} else {
guessList.push(keyPress);
triesLeft--;
}
return element === keyPress;
});
if (remainingMystery <= 0) {
document.getElementById('game-display-area').innerHTML = ('YOU WIN!')
};
console.log('These guesses were correct: ' + found);
};
我要添加的最后一件事是我在学校,所以我敢肯定有一种花哨的方法可以做到这一点,或者可以使用jQuery,但是只有JS应该有一种简单的方法,因为这就是我所要做的全部到目前为止为止还知道:)
我尝试过的其他事情:
var test_array = (secretPuzzleSolution.indexOf(keyPress) > -1);
if (test_array === true) {
console.log(keyPress + ' was found in the puzzle');
for (i = 0; i < puzzleUserSees.length; i++) {
if (keyPress === puzzleUserSees[i]) {
puzzleUserSees.splice([i], keyPress)
}
}
} else {
triesLeft--;
guessList.push(keyPress);
console.log(keyPress + ' was NOT found');
}
谢谢!
答案 0 :(得分:1)
您正在犯一个经典的错误,循环遍历数组以搜索某些内容,并将其视为每个不匹配元素的失败。参见Searching array reports "not found" even though it's found
您不应该使用def filterDF(number, code, d1, d2):
dataFiltered = []
numberNew = 0
for i in range(number):
if code[i] == 'correct':
dataFiltered.append([d1[i],d2[i]])
countNew += 1
newTable = {'countNew' : countNew, 'data' : dataFiltered}
newDf = pd.DataFrame(newTable)
return newDf
from pyspark.sql.types import ArrayType
filterDFudf = sqlContext.udf.register("filterDF", filterDF, "Array<double>")
df2 = df1.select(df1.number, filterDFudf(df1.number, df1.code, df1.d1, df1.d2)).alias('dataNew')
,因为它只会返回第一个比赛的位置。您需要使用.find()
遍历整个数组。它接收元素的数组索引,因此您不需要使用.each()
,它仅返回第一个位置,并且在一个字母可以有多个匹配项时没有用。
.indexOf()