当单词出现故障时,如何使控制台打印错误? Node.js的

时间:2018-03-11 17:41:40

标签: arrays node.js if-statement include var

message == 'john hi'时,当前代码使控制台打印为true,但是当字样乱序时我需要打印false。

array1中的元素应该是第一个,array2中的元素应该是第二个,如果我愿意,我应该能够在array2之后添加更多的数组。

我需要代码做的例子:

message == 'hi john' //打印为真时

message == 'and hey evan' //打印为真时

message == 'john hi' //打印为false时,因为array2是第一个

var array1 = ['hi', 'hello', 'hey']
var array2 = ['john', 'evan', 'matthew']
var message = ''

if (array1.some(element => message.includes(element)) && array2.some(element => message.includes(element))) {
  console.log(true);
}

2 个答案:

答案 0 :(得分:0)

这种方法怎么样,我们寻找每个数组中最后出现的单词。所以这可能是[5,0]。这些应该是有序的,如果它们不是我们拒绝的。

var array1 = ['hi', 'hello', 'hey'];
var array2 = ['john', 'evan', 'matthew'];
var arrayOfArrays = [array1, array2];

function isInOrder(arr)
{  
    for (var i = 0; i < arr.length - 1; i++ ) {
        if (arr[i] > arr[i+1])  return false;
    }
    return true;
}

function wordsAreInOrder(message) {
    var maxIndexes = arrayOfArrays.map((a) => {
          return Math.max.apply(null, a.map((value) => { return message.indexOf(value) }));
    });

    console.log('The latest occurrence of words from each array: ', maxIndexes);

    return isInOrder(maxIndexes);
}

console.log('Is in order: ' + wordsAreInOrder('hi john'));
console.log('Is in order: ' + wordsAreInOrder('and hey evan'));
console.log('Is in order: ' + wordsAreInOrder('john hi'));

答案 1 :(得分:0)

这是一种线性算法,可确保:

  1. 数组1中的单词永远不会出现在数组2的单词后面
  2. 来自阵列2的单词永远不会被击中&#39;在数组1字之前
  3. function checkWordOrder(array1, array2, str) {
        const words = str.split(' ');
        const wordsLength = words.length;
        const array1Length = array1.length;
        const arrayConcat = array1.concat(array2);
        let hitArray1 = false;
        let hitArray2 = false;
    
        for (let i = 0; i < wordsLength; ++i) {
            const index = arrayConcat.indexOf(words[i]);
    
            if (index != -1) { // Word is found in either array
                if (index < array1Length) {
                    if (hitArray2) return false;
                    hitArray1 = true;
                } else if (index >= array1Length) {
                    if (!hitArray1) return false;
                    hitArray2 = true;
                }
            }
        }
    
        return true;
    }
    
    let array1 = ['hi', 'hello', 'hey'];
    let array2 = ['john', 'evan', 'matthew'];
    
    console.log(checkWordOrder(array1, array2, 'hi john'));         // true
    console.log(checkWordOrder(array1, array2, 'and hey evan'));    // true
    console.log(checkWordOrder(array1, array2, 'john hi'));         // false
    console.log(checkWordOrder(array1, array2, 'hi john john hi')); // false
    console.log(checkWordOrder(array1, array2, 'random'));          // true