为什么我必须在javascript“for in”循环中使用==,而不是==?

wribegjk  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(328)

此问题已在此处找到答案

在javascript比较中应该使用哪个等于运算符(==vs===)((48个答案)
为什么在数组迭代中使用“for…in”是个坏主意((27个答案)
两天前关门了。
我在解决基本的算法问题,我陷入了这段代码中。
问题是获取字符串数据并删除重复的字符。例如,输入:“ksekkset”,输出:“kset”
这就是我的解决方案。

  1. function solution(s) {
  2. let answer = "";
  3. for(let i in s) {
  4. if(s.indexOf(s[i]) == i) answer+=s[i];
  5. }
  6. return answer;
  7. }

我的问题是,为什么我只有在if()中加上“==”才能得到正确的答案?当我输入“==”时,为什么if()只返回false?
如果我使用for循环,“==”也可以使用。。

  1. function solution2(s) {
  2. let answer = "";
  3. for(let i=0; i<s.length; i++) {
  4. if(s.indexOf(s[i])===i) answer+=s[i];
  5. }
  6. return answer;
  7. }

我太糊涂了!

9cbw7uwe

9cbw7uwe1#

正如上面提到的@vlaz。。==vs===并不是唯一的区别。
我在您的程序中编写了change,以尝试for/in change和===change的所有组合,您可以看到,唯一一个不能按预期工作的是 === 具有 for / in .
奇怪的是,对于一根弦, for / in 将索引作为字符串提供给您,即使它们是数字!

  1. const s = "stackoverflow"; // repeated 'o' makes answer interesting
  2. const answers = {
  3. answerForInTripple: "",
  4. answerForInDouble: "",
  5. answerForTripple: "",
  6. answerForDouble: "",
  7. };
  8. for(let i in s) {
  9. if(s.indexOf(s[i]) == i) {
  10. answers.answerForInDouble += s[i];
  11. }
  12. if(s.indexOf(s[i]) === i) {
  13. answers.answerForInTripple += s[i];
  14. }
  15. }
  16. for(let i=0; i < s.length; i++) {
  17. if(s.indexOf(s[i]) == i) {
  18. answers.answerForDouble += s[i];
  19. }
  20. if(s.indexOf(s[i]) === i) {
  21. answers.answerForTripple += s[i];
  22. }
  23. }
  24. console.log(answers);
  25. console.log('here is the difference between what you are comparing');
  26. for(let i in s) {
  27. const idx = s.indexOf(s[i]);
  28. console.log(typeof i, i, typeof idx, idx);
  29. }
  30. console.log('simpler example');
  31. for (let i in 'test') console.log(typeof i, i);
展开查看全部

相关问题