如果我在下面的“word”字符串中输入“12314”,一切都会按预期进行。如果我输入“abacd”等字符,代码就会失败。谁能告诉我为什么? (1 in [1,2,3,1,4]) 有效,但是 ('a' in [a,b,a,c,d] 失败。我对 Javascript 还很陌生。
var word = "abacd";
function duplicateEncode(word){
var repeat = [];
var result = [];
var letters = word.split('');
for (i=0; i < letters.length; i++){
if (letters[i] in repeat) {
result.push(")");
} else {
result.push("(");
}
repeat.push(letters[i]);
}
return result;
}
最佳答案
在运算符中:
A string or symbol representing a property name or array index (non-symbols will be coerced to strings).
在您的情况下,它正在工作,因为它查看索引而不是字符串的值。当在数组上使用“in”运算符时,它使用索引作为属性
<小时/>尝试一下:
> 1 in [1,2] //-> true
> 1 in [1] //-> false (only one item in the list
> 1 in [2,2] // -> true
> Object.keys([2,3,4]) // -> ['0', '1', '2' ]
//in your case you would want to use indexOf
>['a','b','c'],indexOf('a') -> 0
>['a','b','c'],indexOf('e') -> -1
<小时/>
要解决您的问题,请将 in
替换为:
for (i=0; i < letters.length; i++){
if (repeat.indexOf(letter[i]) > -1) {
result.push(")");
} else {
result.push("(");
}
repeat.push(letters[i]);
}
关于Javascript:数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39490418/