我有一个看起来有点像这样的多维数组:
var basketData = [
["Image name","image_path", "image_long_path"],
["Image another name","image_path", "image_long_path"],
["Image different name","image_path", "image_long_path"],
]
我需要在点击时删除与第一个元素匹配的整个子数组。
我设法编写了一个函数,用于识别子数组中是否存在imageName
:
function removeFromBasket(imageName) {
console.log('Removing ' + imageName);
for (i = 0; i < basketData.length; i++) {
if (basketData[i].indexOf(imageName) != -1) {
// it exists in the array
} else {
// it doesn't exist
}
因此,如果index
存在,则0
将返回-1
,如果不存在,则0
将返回basketData[i].splice(basketData[i].indexOf(imageName), 1);
。但是,现在我需要删除识别此索引的子数组。这是我意识到我出错的地方。
执行以下操作只删除此数组中匹配的索引,这很愚蠢,因为我已经知道如果它存在,它将成为imageName
,因为它是唯一的地方找到数据:
<a href="#">{{ HTML::image("img/logo.png", "Logo") }}</a>
因此它只删除子数组的第一个元素,而不是删除整个子数组。
那么,如何通过迭代子数组来删除找到{{ html_entity_decode( HTML::link("#", HTML::image("img/logo.png", "Logo") ) ) }}
的整个子数组,直到找到匹配的元素?
答案 0 :(得分:2)
使用filter()。在过滤器回调中,您可以检查整个子阵列的indexOf
var imageName = "Image another name";
var basketData = [
["Image name", "image_path", "image_long_path"],
["Image another name", "image_path", "image_long_path"],
["Image different name", "image_path", "image_long_path"],
];
// New function syntax! Supported in all modern browsers except for Safari
var result = basketData.filter(innerArray => innerArray.indexOf(imageName) == -1);
console.log(result);
document.getElementById('p').innerHTML = JSON.stringify(result, null, 2);
<pre id='p'></pre>
答案 1 :(得分:0)
var basketData = [
["Image name", "image_path", "image_long_path"],
["Image another name", "image_path", "image_long_path"],
["Image different name", "image_path", "image_long_path"],
]
function removeFromBasket(imageName) {
console.log('Removing ' + imageName);
for (i = basketData.length - 1; i > 0; i--) {
if (basketData[i].indexOf(imageName) != -1) {
basketData.splice(i, 1);
}
else {
}
}
}
当我们在for循环中拼接时,我们破坏了我们用来引用数组中其他元素的索引。我们可以使用 - 而不是++来反转for循环。 因为我们从顶部开始,所以当您开始永久删除和移动
中的值时,没有任何值会被扰乱答案 2 :(得分:0)
var basketData = [
["Image name", "image_path", "image_long_path"],
["Image another name", "image_path", "image_long_path"],
["Image different name", "image_path", "image_long_path"],
]
var deleteBasket = function (name) {
for (i=0; i<basketData.length; i++){
if (basketData[i][0] === name){
basketData.splice(i--,1);
}
else {
}
};
}
deleteBasket("Image another name");
console.log(basketData);