我一直在尝试删除数组的特定部分,我认为我有它工作。但我无法弄清楚为什么我不能删除第一条记录。
如果我将arrayToDelete设置为67(表示第二个数组的第一个元素)或9(表示第三个数组的第一个元素)......它可以正常工作。但是如果我将arrayToDelete更改为7(表示第一个数组的第一个元素),它就不会删除那个。
我哪里错了?
var mainArray = [];
var a = [7,"red","Q","gtgtg"];
mainArray.push(a);
var b = [67,"blue","s","ghft"];
mainArray.push(b);
var c = [9,"green","t","rtryt"];
mainArray.push(c);
var pickle = JSON.stringify(mainArray);
console.log("starting array - "+pickle);
console.log("starting array length - "+mainArray.length);
var arrayToDelete = "67";
var getLoc = "";
// Get position of array where first value is "1"
for (var i = 0; i < mainArray.length; i++) {
//console.log(mainArray[i][0]);
if(mainArray[i][0] == arrayToDelete){
//console.log("array number "+i);
getLoc = i;
}
}
console.log("that number was spotted in position - "+getLoc);
//Delete from
if(getLoc != "" && getLoc != "-1"){
mainArray.splice(getLoc, 1);
}
var pickle2 = JSON.stringify(mainArray);
console.log("Array after removal - "+pickle2);
console.log("ending array length - "+mainArray.length);
答案 0 :(得分:5)
您的错误在getLoc != ""
。对于false
,这是getLoc === 0
。
我知道js不是一种强类型的语言,但如果你用强类型的等式检查书写你会更好===
参见例如这篇文章提供了有关该主题http://www.sitepoint.com/borrowing-techniques-strongly-typed-languages-javascript/的更多见解,并且它始终是通过静态代码分析器(例如http://jslint.com或http://jshint.com)来破坏代码的不错选择。
答案 1 :(得分:2)
在console.log(getLoc != "")
之前添加//Delete from
,当getLoc = 0时,您会看到打印 false 。
更改
console.log("that number was spotted in position - "+getLoc);
//console.log(getLoc != "")
//Delete from
if(getLoc != "" && getLoc != "-1"){
mainArray.splice(getLoc, 1);
}
通过
console.log("that number was spotted in position - "+getLoc);
//console.log(getLoc !== "")
//Delete from
if(getLoc !== "" && getLoc != "-1"){
mainArray.splice(getLoc, 1);
}
答案 2 :(得分:1)
在这种情况下,功能方法可能更具可读性:
mainArray = mainArray.filter(arr => arr[0] !== arrayToDelete);