我有js数组,我使用它作为地图它是动态的(在这个例子中它不是) 所以我不知道它会有多少元素 我想删除所有发现的元素 这是循环后数组的最终视图
movmet_sequence_history:[]
movmet_sequence_history["0"] = "A"
movmet_sequence_history["1"] = "B"
movmet_sequence_history["2"] = "C"
movmet_sequence_history["3"] = "D"
....
....
....
....
movmet_sequence_history["20"] = "Z"
if(movmet_sequence_history["2"] == "C")
{
//HERE I WANT TO REMOVE THE ELEMENTS "2" ,"1" ,"0"
//Only the movmet_sequence_history["3"] = "D" will remain
}
更新 我不手动删除正确的元素 正如我所说,阵列是动态的,我不知道有多少元素将由找到的
组成答案 0 :(得分:2)
你可以将它们定义为未定义。
movmet_sequence_history:[]
movmet_sequence_history["0"] = "A"
movmet_sequence_history["1"] = "B"
movmet_sequence_history["2"] = "C"
movmet_sequence_history["3"] = "D"
if(movmet_sequence_history["2"] == "C")
{
movmet_sequence_history["0"] = undefined;
movmet_sequence_history["1"] = undefined;
movmet_sequence_history["2"] = undefined;
//Only the movmet_sequence_history["3"] = "D" will remain
}
答案 1 :(得分:1)
使用delete
运算符。
delete
运算符会从对象中删除属性。
var movement_sequence_history = ["A", "B", "C", "D" ];
if (movement_sequence_history["2"] == "C") {
delete movement_sequence_history[0];
delete movement_sequence_history[1];
delete movement_sequence_history[2];
}
console.log(movement_sequence_history);

答案 2 :(得分:0)
您可以使用array.splice
+ array.fill
。您可以为array.splice提供索引,它将删除该索引之后的所有项并返回它们。
现在你只需清除原始数组中的所有值,并将从splice返回的数组合并到它。
var movmet_sequence_history = []
movmet_sequence_history["0"] = "A"
movmet_sequence_history["1"] = "B"
movmet_sequence_history["2"] = "C"
movmet_sequence_history["3"] = "D"
function removeChar(str) {
var index = movmet_sequence_history.indexOf(str)
var _t = movmet_sequence_history.splice(index+1);
movmet_sequence_history.fill(undefined)
movmet_sequence_history = movmet_sequence_history.concat(_t)
console.log(movmet_sequence_history)
}
<button onclick="removeChar('A')">Remove A</button>
<button onclick="removeChar('B')">Remove B</button>
<button onclick="removeChar('C')">Remove C</button>
<button onclick="removeChar('D')">Remove D</button>