为什么这个.indexOf方法不适用于这个数组?

时间:2017-03-12 17:19:00

标签: javascript arrays methods

我有以下代码:

var newArr = [];

function mutation(arr) {

  //Makes both values lowercase

  for (var i = 0; i < arr.length; i++) {

    newArr.push(arr[i].toLowerCase());

  }

  //splits the letters of the second value into separate values.

  var letters = [];
  letters.push(newArr[1]);
  letters = letters.toString();
  letters = letters.split('');

  //checks to see if there is a letter that isn't in the first value.

  for (var j = 0; j < letters.length; j++) {

    if (newArr[1].indexOf(letters[j]) == -1) {

      return false;

    }

  }

  return true;

}

mutation(["voodoo", "no"]);

它的作用类似于([“hello”,“hey”]),但它不适用于上述方法。为什么.indexOf方法不能在这个数组上工作?

1 个答案:

答案 0 :(得分:0)

我真的不知道代码应该做什么,但让我们一步一步地检查:

var newArr = [];

function mutation(arr) {

  // Makes both values lowercase
  // arr is now ["voodoo", "no"]

  for (var i = 0; i < arr.length; i++) {

    newArr.push(arr[i].toLowerCase());

  }
  // newArr has the same content: ["voodoo", "no"]
  //splits the letters of the second value into separate values.

  var letters = [];
  letters.push(newArr[1]); // letters is now ["no"]
  letters = letters.toString(); // letters is now "no"
  letters = letters.split(''); // letters is now ["n", "o"]

  //checks to see if there is a letter that isn't in the first value.

  for (var j = 0; j < letters.length; j++) { // foreach ["n", "o"]

    if (newArr[1].indexOf(letters[j]) == -1) { // "no".indexOf("n") and "no".indexOf("o") is always > -1 


      return false; // so false is never returned

    }

  }

  return true; // true is always returned

}

mutation(["voodoo", "no"]);

我认为你应该改变

if (newArr[1].indexOf(letters[j]) == -1)

if (newArr[0].indexOf(letters[j]) == -1)

如果你想测试第一个单词中是否包含第二个单词的一个字母。