我想拼接数组的多个索引,这是我的代码示例:
let arrayA = ["aa","bb","cc","dd","ee","ff","gg","hh"];
let arrrayIndexSplice = [0,1,3];
let test = null;
for (let i of arrrayIndexSplice) {
test = arrayA.splice(i,1);
}
console.log(arrayA);
预期结果是[“ cc”,“ ee”,“ ff”,“ gg”,“ hh”];
实际结果是[“ bb”,“ dd”,“ ee”,“ gg”,“ hh”]
答案 0 :(得分:1)
拼接时,所有后续值的索引都会减少。因此,拼接出最后一个:
let arrrayIndexSplice = [0, 1, 3];
for (let i of arrrayIndexSplice.sort().reverse()) {
arrayA.splice(i, 1);
}
或者只是过滤:
arrayA = arrayA.filter((_, i) => !arrayIndexSplice.includes(i));
答案 1 :(得分:1)
您应该从结尾开始,即- 让我们尝试关注
let arrayA=["aa","bb","cc","dd","ee","ff","gg","hh"];
let arrrayIndexSplice=[0,1,3];
for (let i=arrrayIndexSplice.length-1;i>=0;i--){arrayA.splice(arrrayIndexSplice[i],1)}
答案 2 :(得分:0)
问题可能是您以升序遍历数组。因此,当您拼接第一个元素时,其他元素的索引也会改变。对数组进行负迭代可能会有所帮助。
let arrayA=["aa","bb","cc","dd","ee","ff","gg","hh"];
let arrrayIndexSplice=[0,1,3];
for (let i=arrrayIndexSplice.length-1; i > -1; i--){arrayA.splice(i,1)}
答案 3 :(得分:0)
您可以过滤出所有要排除索引的元素。
let arrayA = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh"];
let arrrayIndexSplice = [0, 1, 3];
arrayA = arrayA.filter((item, index)=> !arrrayIndexSplice.includes(index));
console.log(arrayA);
答案 4 :(得分:0)
我的想法是用特殊字符或字符串替换该索引中的项目,然后再次使用replace删除该特殊字符或字符串:
let arrayA = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh"];
let arrrayIndexSplice = [0, 1, 3];
let test = null;
arrayA.forEach((val, index) => {
if(arrrayIndexSplice.includes(index)){
arrayA[index] = '##';
}
});
arrayA = arrayA.join(',').replace(/##,/g, '').split(',');
console.log(arrayA);
答案 5 :(得分:-1)
遍历for of
循环时,您会不断更改数组本身,因此索引会在每个循环步骤向右移
您的示例
arrayA: ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh"]
// start loop
// 1st iteration
// test = arrayA.splice(i,1);
test = 0
arrayA = ["bb", "cc", "dd", "ee", "ff", "gg", "hh"] // index 0 removed
// 2nd iteration
// test = arrayA.splice(i,1);
test = 1
arrayA = ["bb", "dd", "ee", "ff", "gg", "hh"] // index 1 removed
// 3rd iteration
// test = arrayA.splice(i,1);
test = 3
arrayA = ["bb", "dd", "ee", "gg", "hh"] // index 3 removed
这有效:您需要获取当前arrrayIndexSplice
元素的索引,以便可以将拼接起始索引减少该数量
console.clear()
let arrayA = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh"];
let arrrayIndexSplice = [0, 1, 3];
for (let k in arrrayIndexSplice) {
if (arrrayIndexSplice.hasOwnProperty(k)) {
arrayA.splice(arrrayIndexSplice[k]-k, 1)
}
}
console.log(arrayA)
这也有效:它不适用于循环,但可以使用filter
函数
let arr = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh"];
let indices = [0,1,3]
function filterIndices(arr, indices, swap = false) {
return arr.filter((item, index, source) => {
return swap ? !indices.includes(index) : indices.includes(index);
})
}
newArr = filterIndices(arr, indices, true)
console.log(newArr)
答案 6 :(得分:-2)
您可以使用以下代码:
let arrayA = ["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh"];
let arrrayIndexSplice = [0, 1, 3];
for (let i of arrrayIndexSplice.length) {
arrayA.splice(arrrayIndexSplice[i], 1)
}