我有下一个 python 代码:
-rwSrw-rw-
因此,我正在尝试在 JS 中执行相同的操作:
.secretshell
但是,它不起作用!
答案 0 :(得分:2)
您可以使用Array.includes()检查某个元素是否属于数组,然后使用for ... of循环遍历字符串并执行以下操作:
const letter = ['a', 'b', 'c', 'd'];
const word = "Black";
for (const char of word)
{
if (letter.includes(char))
console.log(char);
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 1 :(得分:1)
本着功能性python的精神,我建议使用filter
,因为它的工作方式类似于python中的filter
。问题在Python和Javascript上都存在,所以:)
var letter = ['a', 'b', 'c', 'd'];
var word = "Black";
var filtered = word.split("").filter(x => letter.includes(x))
console.log(filtered)
答案 2 :(得分:0)
您实际上并不需要第二个for循环。只需检查单词[i]是否在字母数组中,就可以使用“ includes”或“ indexOf”来做到这一点。
var letter = ['a', 'b', 'c', 'd'];
var word = "Black";
var dictionary = [];
var dictionaryCoincidence = [];
for (var i = 0; i < word.length; i++) {
dictionary.push(word[i]);
if (letter.includes(word[i])) {
dictionaryCoincidence.push(dictionary[i]);
}
}
console.log(dictionary); console.log(dictionaryCoincidence);
答案 3 :(得分:0)
您必须使用两个循环: 一个循环用于字典,一个循环用于这样的字母:
var letter = ['a', 'b', 'c', 'd'];
var word = "Blackd";
var dictionary = [];
var dictionaryCoincidence = [];
for (var i = 0; i < word.length; i++) {
dictionary.push(word[i]);
}
for (var i = 0; i < dictionary.length; i++) {
for(var j = 0; j < letter.length ; j++){
if (dictionary[i] == letter[j]) {
dictionaryCoincidence.push(dictionary[i]);
}
}
}
console.log(dictionary);
console.log(dictionaryCoincidence);
答案 4 :(得分:0)
尝试将第二个循环更改为
for (var i = 0; i < dictionary.length; i++) {
if (letter.includes(dictionary[i])) {
dictionaryCoincidence.push(dictionary[i]);
}
}
您需要检查字典[i]是否在字母数组中,而不是等于字母[i]