我使用以下代码向我的数组添加新值。 但是,我希望能够在某次匹配后插入值。
var Arr = [];
a = document.getElementById("f").value;
b = document.getElementById("s").value;
c = document.getElementById("t").value;
Arr.push([f,s,t])
例如,如果我的数组中的第一个元素包含的值等于" a"中的值,我会喜欢新值(" a&# 34;)在数组
中最后一次出现该特定值后立即插入例如以下数组:
["OPEL", "BLACK", "4"]
["OPEL", "BLUE", "5"]
["OPEL", "RED", "4"]
["FIAT", "BLACK", "5"]
["FIAT", "WHITE", "5"]
["FORD", "GREY", "4"]
现在我想插入以下内容:
["FIAT", "ORANGE", "4"]
需要在最后一次出现" FIAT"后插入,结果将是:
["OPEL", "BLACK", "4"]
["OPEL", "BLUE", "5"]
["OPEL", "RED", "4"]
["FIAT", "BLACK", "5"]
["FIAT", "WHITE", "5"]
["FIAT", "ORANGE", "4"]
["FORD", "GREY", "4"]
有什么想法吗?
答案 0 :(得分:1)
正如您所建议的,我们有以下数组:
var arr = [
["OPEL", "BLACK", "4"],
["OPEL", "BLUE", "5"],
["OPEL", "RED", "4"],
["FIAT", "BLACK", "5"],
["FIAT", "WHITE", "5"],
["FORD", "GREY", "4"]
];
然后,我们希望在最后一次出现具有相同第一个元素的数组之后放入以下子元素:
var child = ["FIAT", "ORANGE", "4"];
要做到这一点,我们只是遍历数组,然后在找到与第一个元素相同的数组后插入child
,然后我们找到第一个没有相同第一个元素的数组。如果我们还没有在数组的末尾插入它,我们会在最后插入它。
//Create an insert method of arr:
arr.insert = function(child) {
//This Bool is true iff we've found an array that has the same first element as it:
var foundSameFirstElement = false;
//Traverse arr:
for (var i = 0; i < this.length; i++) {
//If we haven't found an array with the same first element as child and this element has the same first element as child, then set foundSameFirstElement to true:
if (!foundSameFirstElement && this[i][0] === child[0]) {
foundSameFirstElement = true;
}
//If we have found an array with the same first element as child and this element does not have the same first element as child, then insert child into the array here and break to exit the loop:
if (foundSameFirstElement && this[i][0] !== child[0]) {
this.splice(i, 0, child);
break;
}
}
//If i is this.length, then we traversed the whole loop without breaking, meaning we haven't inserted child yet. Thus, if i is this.length, insert child at the end:
if (i === this.length) this.splice(this.length, 0, child);
};
//Now to finish it off, pass child through arr.insert:
arr.insert(child);
//If we check the value of arr, it is just like how we want it to be, with child as index 5:
console.log(arr);