JavaScript数组的字符串不比较

时间:2017-01-31 05:32:33

标签: javascript arrays string compare equality

该程序应该从2个文本文件中获取输入。第一个包含数据对,每对都在其自己的文本行上。第一个是单词,第二个是表示权重的数字。第二个文件是每个单独的单词列表。我测试了输入流,我知道文件正在输入到每个数组中。当我去比较字符串的组合时,这些单词在它们应该的时候不会相等。我检查过以确保它们是基本字符串而不是对象。我尝试过==,===和localeCompare()但没有成功。我修剪了字符串,使用了valueOf()和toString()也无法正常工作。任何帮助将不胜感激。

<!-- File:  Enter filename -->
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <title>Mod D 3: Revenge of the JS</title>
</head>

<body>
  <input onchange="loadFile(id)" type="file" name="fileName" id="firstFile" accept=".txt">
  <br>
  <input onchange="loadFile(id)" type="file" name="fileName2" id="secondFile" accept=".txt">
  <br>
  <br>
  <button onclick="compareFiles()">compare files</button>
  <br>
  <br>

  <textarea readonly name="textStuff" id="textStuff" cols="30" rows="15" style="resize none;" data-role="none"></textarea>
  <script>
    var display = document.getElementById("textStuff");
    var file1Words = [];
    var file1Weight = [];
    var file2Words = [];
    var words = [];
    var testingFiles = false;

    function loadFile(idname) {
      console.log("arrived at load function");
      var file = document.getElementById(idname).files[0];
      var reader = new FileReader();
      reader.onload = function(progressEvent) {
        var lineNum = this.result.split('\n');
        if (idname == 'firstFile') {
          console.log("found the first file");
          for (var i = 0; i < lineNum.length; i++) {
            var holder = lineNum[i].split(" ");
            console.log("loading...");
            file1Words.push(holder[0]);
            file1Weight.push(Number(holder[1]));
          }
        } else if (idname == 'secondFile') {
          console.log("found second file");
          for (var i = 0; i < lineNum.length; i++) {
            console.log("loading...");
            file2Words.push(lineNum[i]);
          }
        }
      };
      reader.readAsText(file);
    };

    function compareFiles() {
      console.log("in the compare function");
      if (file1Words.length == 0 || file2Words.length == 0) {
        console.log("why no stuff");
        alert("You must input both files");
        return;
      }
      if (testingFiles) {
        console.log("testing the files");
        display.value = "";
        for (var i = 0; i < file1Words.length; i++) {
          display.value += file1Words[i] + " " + file1Weight[i] + '\n';
        }
        for (var i = 0; i < file2Words.length; i++) {
          display.value += file2Words[i];
        }
      }

      // loop through the arrays
      for (var i = 0; i < file1Words.length; i++) {
        var s1 = file1Words[i];
        for (var j = 0; j < file2Words.length; j++) {
          //console.log(file1Words[i] + " " + file2Words[j]);
          var s2 = file2Words[j];
          console.log(s1 + " " + s2);
          console.log(s1.localeCompare(s2));
          if (s1.localeCompare(s2) == 0) {
            console.log("found something. sending to next func");
          }
        }
      }

    };

    function compareToSaved() {
      console.log("found a match. comparing to see if top 15");
    };
  </script>

</body>

</html>

2 个答案:

答案 0 :(得分:1)

在第二个单词list-file2Words中, 最后还添加了回车符。

所以第二个file2Words总是比file1Words多一个字符。

您可以通过打印两个数组中的字符串长度来检查这一点。 如下图所示。

此外,这会将file2Words的最后一个char的ascii代码打印为13(回车)

multiplyMatrix

要处理此问题,请在将其添加到列表之前使用trim(),如其他答案中所述。

答案 1 :(得分:0)

在将每个 LINE内容推送到数组之前,您需要trim()

var holder = lineNum[i].trim().split(" ");
file2Words.push(lineNum[i].trim());

var display = document.getElementById("textStuff");
var file1Words = [];
var file1Weight = [];
var file2Words = [];
var words = [];
var testingFiles = false;

function loadFile(idname) {
	console.log("arrived at load function");
	var file = document.getElementById(idname).files[0];
	var reader = new FileReader();
	
	reader.onload = function (progressEvent) {
		var lines = this.result.split('\n');
		
		if (idname == 'firstFile') {
			console.log("found the first file");
			
			lines.forEach(line => {
				var values = line.trim().split(" ");
				file1Words.push(values[0]);
				file1Weight.push(Number(values[1]));
			});
		} else if (idname == 'secondFile') {
			
			console.log("found second file");
			lines.forEach(line => {
				file2Words.push(line.trim());
			});
		}
	};
	
	reader.readAsText(file);
};

function compareFiles() {
	console.log("in the compare function");
	console.log(file1Words, file2Words);

	if (file1Words.length == 0 || file2Words.length == 0) {
		
		console.log("why no stuff");
		alert("You must input both files");
		return;
	}
	if (testingFiles) {
	
		console.log("testing the files");
		display.value = "";
		file1Words.forEach((element, index) => {
			display.value += element + " " + file1Weight[index] + '\n';
		});
		
		file2Words.forEach((element, index) => {
			display.value += element + '\n';
		});
	}

	// loop through the arrays
	for (var i = 0; i < file1Words.length; i++) {
		var s1 = file1Words[i];
		for (var j = 0; j < file2Words.length; j++) {
			var s2 = file2Words[j];
			var result = s1 === s2;
			console.log(s1 + " ==? " + s2, result);
			if (result) {
				console.log("found something. sending to next func");
			}
		}
	}

};

function compareToSaved() {
	console.log("found a match. comparing to see if top 15");
};
<!-- File:  Enter filename -->
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <title>Mod D 3: Revenge of the JS</title>
</head>

<body>
  <input onchange="loadFile(id)" type="file" name="fileName" id="firstFile" accept=".txt">
  <br>
  <input onchange="loadFile(id)" type="file" name="fileName2" id="secondFile" accept=".txt">
  <br>
  <br>
  <button onclick="compareFiles()">compare files</button>
  <br>
  <br>

  <textarea readonly name="textStuff" id="textStuff" cols="30" rows="15" style="resize none;" data-role="none"></textarea>

</body>

</html>