我正在尝试使用splice
提取嵌套数组。我得到的是每个元素上带有undefined
的所需大小的数组
var testCurrProds = [ 'Prod1', 'prduct1', 'Prod1']
var testCurrProds1 = [ 'Prod2', 'prduct2', 'Prod2', 'Prod2', "Prod9"]
var testCurrProds2 = [ 'Prod3', 'prduct3', 'Prod3', 'Prod3', "Prod9"]
var testCurrProds3 = [ 'Prod4', 'prduct4', 'Prod4', 'Prod4', "Prod9", "Prod9", "Prod98"]
var testString = [1, 'tName1', 4, 69, 'Haircare', "T1", "false", "false", testCurrProds]
var testString1 = [2, 'tName2', 1, 69, 'Skincare', "T1", "false", "true", testCurrProds1]
var testString2 = [3, 'tName3', 3, 69, 'Haircare', "T1", "true", "true", testCurrProds2]
var testString3 = [4, 'tName4', 5, 69, 'Skincare', "T1", "true", "false", testCurrProds3]
var testPackages = [testString, testString1, testString2, testString3];
var currPackage = popArray(testPackages, 1, 'tName1');
console.log(currPackage);
function popArray(x, findID, findName)
{
//return array containing submitted ID
for (var k = 0; k < x.length; k++ )
{
//console.log(x[k]);
if((x[k][0]==findID) & (x[k][1]==findName))
{
//var temp = x.splice(k,1)
//console.log(temp);
return x.splice(k,1);
}
}
}
答案 0 :(得分:1)
这里可以使用数组推导,我认为比迭代方法更容易理解,并且更不容易出错。
function popArray(arrayOfArrays, findID, findName) {
const index = arrayOfArrays.findIndex(a => a[0] == findID && a[1] == findName);
return index !== -1 && arrayOfArrays.splice(index, 1)[0];
}
基本上,这只是使用内置的findIndex函数来找到匹配项,然后将其从数组中剪接并返回。
答案 1 :(得分:0)
分析代码后,我没有发现逻辑和代码有任何问题,只不过您对'and'逻辑条件使用了单个'&'符号。
function popArray(x, findID, findName)
{
//return array containing submitted ID
for (var k = 0; k < x.length; k++ )
{
//console.log(x[k]);
if((x[k][0]==findID) && (x[k][1]==findName))
{
var temp = x.splice(k,1)
console.log(temp);
//return x.splice(k,1);
}
}
}
查看此附件图像。我运行了这段代码并获得了预期的输出。 http://prntscr.com/m0baai