[英]Remove an object from an array?
我有這個應用程序,可以讓用戶選擇他的顏色首選項,並在以后決定更改它們時進行更改。 該應用程序無需在頁面重新加載之間工作。 我希望用戶能夠從下拉列表中刪除特定的顏色首選項。 我想使用indexOf和splice,但是我一直在努力使用它。 這是我到目前為止的工作。 問題出在Remove()中。 JS Bin: http : //jsbin.com/ANENaRid/2/
這是故障功能:
function Remove() {
var select = document.getElementById("selectColor");
for (var i = 0; i < colors.length; i--) {
var selectIndex = colors.indexOf(select.value);
if (selectIndex !== -1) {
colors.splice(i, 1);
}
return false;
}
}
remove函數應該看起來像這樣,您也必須從select中刪除該選項(僅構造函數名稱應為大寫):
function remove() {
var select = document.getElementById("selectColor");
for (var i = 0; i < colors.length; i++) {
if (colors[i].name_prop == select.value) {
colors.splice(i, 1);
}
}
}
function Remove() {
var select = document.getElementById("selectColor");
var selectIndex = colors.indexOf(select.value);
if (selectIndex !== -1) {
colors.splice(selectIndex , 1);
}
return false;
}
而不是遍歷顏色數組,您應該只選擇要刪除的顏色。 您獲得該項目的索引並將其刪除。 無需迭代。
使用之一
for(var i = 0; i < colors.length; i++) {
//your code here
}
要么
for(var i = colors.length-1; i >= 0; i--) {
//your code here
}
在你的循環
並將return
語句放入if
塊的內部
您可以改為調用表單重置功能。
刪除示例元素的樣式屬性!
這可能會有所幫助:
for (var i = 0; i < colors.length; i++) {
var index = colors[i].name_prop.indexOf(select.value);
if (index !== -1) {
colors.splice(i, 1);
return false;
}
}
indexOf
可能是無用且不可靠的。 但我懶得進一步調查,請以其他方式查看此答案: https : //stackoverflow.com/a/20900571/1636522 。
我重構了您的刪除功能;
function Remove () {
var selectedIndex = document.getElementById("selectColor").selectedIndex;
var options=document.getElementById("selectColor").options;
for(var i = 0; i < options.length; i++) {
if(options[selectedIndex].text === colors[i].name_prop){
alert(colors[i].name_prop + "removed");
colors.splice(i, 1);
return false;
}
}
}
它從顏色數組中刪除選定的項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.