删除关联数组中的元素

时间:2018-01-05 01:14:33

标签: javascript arrays

我正在尝试创建一个按钮,以便在单击时,存储在关联数组中的特定元素将被删除。但我所做的似乎并不奏效。任何帮助将不胜感激。

  // Creates the button
  bodyText = bodyText + '<input type="button" id="btnDeleteQuestion" 
  value="Delete a question">';

  document.getElementById("btnDeleteQuestion")
    .addEventListener("click", function() {
      // Deletes the third question stored in the questionBank
      delete questionBank[2]['questionText'];
      console.log(questionBank);  
    });
}

2 个答案:

答案 0 :(得分:1)

使用splice(如果是数组)从数组中删除元素。

questionBank.splice(2, 1); // from the third element, remove 1 item.

您在问题中所写的内容将获得questionBank[2],然后在对象中删除名为property的{​​{1}}。

如果数组没有至少3个项目或者第3个项目是questionTextnull

,它也会抛出错误

答案 1 :(得分:0)

我希望你能提供帮助

set.seed(24)
df1 <- data.frame(col1 = sample(c(TRUE, FALSE), 10, replace = TRUE),
     col2 = c(1:8, "Good", 10), col3 = as.character(1:10),
 stringsAsFactors = FALSE)