将数组 [in] 从 for 循环存储到返回未定义的新数组
Posted
技术标签:
【中文标题】将数组 [in] 从 for 循环存储到返回未定义的新数组【英文标题】:Storing array[i] from forloop to a new array returning undefined 【发布时间】:2017-09-30 16:57:07 【问题描述】:我目前正在研究一种匹配算法,它将一个字符串数组与另一个字符串数组进行匹配。如果完全匹配 (===),它将结果存储到 unSafeResult 数组中。如果它通过 Regex 匹配,它将将结果存储在warningResult数组中。但是当我使用console.log(warningResult)时。它显示
warning (2) [undefined × 1, "SUGAR.↵CHOCOLATE LIQUOR"]
main.js:41867 warning (3) [undefined × 2, "HYDROGENATED VEGETABLE↵OIL"]
main.js:41867 warning (6) [undefined × 5, "RAPESEED OIL"]
main.js:41867 warning (7) [undefined × 6, "PALM OIL"]
main.js:41867 warning (8) [undefined × 7, "SUNFLOWER OIL"]
main.js:41867 warning (11) [undefined × 10, "RAPESEED OIL"]
main.js:41867 warning (12) [undefined × 11, "PALM OIL"]
然后如果尝试将数组传递到另一个页面,它只会返回 1 个元素,即
[undefined × 11, "PALM OIL"]
有什么办法可以解决这个问题吗?预期的输出应该是它们都应该在一个数组下
"HYDROGENATED VEGETABLE↵OIL"
"RAPESEED OIL"
"PALM OIL"
"SUNFLOWER OIL"
"RAPESEED OIL"
"PALM OIL"
下面是代码
matchText(array)
for(var i = 0; i < 1; i++)
var label = this.labels[i];
var ingredients = label.description.toString().split(/[(,)]/igm).map(function (ingredients)return ingredients.trim(), );
let ingredientList:string[] = ingredients;
let ingredientUpdatedList:string[];
for(var k = 0; k<ingredientList.length; k++)
if(ingredientList[k] === "")
ingredientList = ingredientList.filter((ingredientList) =>
return ingredientList.trim() != '';
);
for(var j = 0; j<ingredientList.length; j++)
let allergy:string[] = ["OIL","SUGAR"];
var unSafeResult = [];
for(var e = 0; e<allergy.length; e++)
var regexp = new RegExp(allergy[e], "igm");
if(ingredientList[j] == allergy[e])
unSafeResult[j] = ingredientList[j];
console.log('unSafe',unSafeResult);
if(ingredientList[j].match(regexp))
this.counter++;
var warningResult = [];
warningResult[j] = ingredientList[j].valueOf(); //here is the issue
console.log('warning', warningResult);
//console.log('Match');
//console.log('Ingredients that matched',unSafeResult);
else
//console.log('No Match');
if(this.counter >0)
this.navCtrl.push(UnSafePage,unSafeResult,warningResult);
else
this.navCtrl.push(SafePage);
【问题讨论】:
【参考方案1】:undefined
的原因:
当你定义一个空数组,并通过索引大于0为array
设置一些东西时,它将被undefined
自动填充直到索引你用过。
确认示例:
var testArr = [];
testArr[5] = 'test';
console.log(testArr);
解决方案:
你应该从for-loop
中定义warningResult
,并根据你的其他条件推送项目。
var ingredientList = ["HYDROGENATED VEGETABLE↵OIL",
"RAPESEED OIL",
"PALM OIL",
"SUNFLOWER OIL",
"RAPESEED OIL",
"PALM OIL"
];
var warningResult = [];
for (var j = 0; j < ingredientList.length; j++)
// only aviable in for loop
//var warningResult = [];
//warningResult[j] = ingredientList[j].valueOf();
warningResult.push(ingredientList[j].valueOf());
console.log('warning', warningResult);
【讨论】:
您好,感谢您的帮助和解答。简洁明了,代码现在就像一个魅力! @GX-X 很高兴为您提供帮助 :) 使用for
循环时,最好使用块范围形式(for (let i = 0;...
) 或在顶层声明循环变量。 var
是函数作用域而不是块作用域。以上是关于将数组 [in] 从 for 循环存储到返回未定义的新数组的主要内容,如果未能解决你的问题,请参考以下文章
2018-06-15for与数组/for-in与数组/一维二维多维数组