【问题标题】:JavaScript | undifined index [duplicate]JavaScript |未定义的索引[重复]
【发布时间】:2021-03-02 09:37:12
【问题描述】:

我卡了一段时间,不知道如何修复此代码。任何帮助表示赞赏

let firstArray = ["oranges", "milk", "eggs", "chocolate"]; // First Array
let secondArray = ["milk", "popcorn", "chocolate", "ham"]; // Second Array

let newArray = []; // New Array that will hold the values that are NOT in other array
debugger;
for(let i = 0; i < firstArray.length; i++){ 
    for(let j = 0; j < secondArray.length; j++){
        if(firstArray[i] !== secondArray[j]){ 
            newArray.push(newArray[i]);  // If oranges != milk > add new item > newArray = ['oranges']
        }else if(firstArray[i] !== secondArray[j]){
            newArray.push(newArray[j]);  // If milk != oranges > add new item > newArray = ['oranges']
        }
    }
}

console.log(newArray); // Print the new array

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    看看includes()函数here

    let firstArray = ["oranges", "milk", "eggs", "chocolate"]; // First Array
    let secondArray = ["milk", "popcorn", "chocolate", "ham"]; 
    let newArray=[];
    for(let i = 0; i < firstArray.length; i++){ 
        if(!secondArray.includes(firstArray[i])) {
        newArray.push(firstArray[i]);
        }   
    }
    console.log(newArray);

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2014-01-27
      • 2012-06-04
      • 2019-06-26
      相关资源
      最近更新 更多