JavaScript |未定义的索引[重复]
Posted
技术标签:
【中文标题】JavaScript |未定义的索引[重复]【英文标题】:JavaScript | undifined index [duplicate] 【发布时间】: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
【问题讨论】:
【参考方案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);
【讨论】:
以上是关于JavaScript |未定义的索引[重复]的主要内容,如果未能解决你的问题,请参考以下文章
会话 ID 未显示错误消息注意:未定义索引:用户 ID [重复]