如何删除Javascript数组中的最后一项?

时间:2018-01-12 19:51:59

标签: javascript jquery arrays

我正在为代码创建自动建议。我有以下代码:

// create tags array
tags = inputval.split(' ');
// remove last word
tags = tags.splice(0, tags.length-1);
// array to string
tags = tags.join();
// replace commas with spaces
tags = tags.replace(',', ' ');

想法是从数组中删除最后一项,因为用户已编写的内容将被替换为所选的单词(标记)。

出于某种原因,当有超过3个标签时,逗号会一直显示在输出中。当我记录标签数组(分割后)时,它看起来像这样:[' tag1',' tag2,tag3,tag4',' tag5']我不知道#39;了解原因。

也欢迎其他解决方案。

更新

我改变了这样的代码,现在它就像一个魅力:

// create tags array
tags = inputval.split(' ');
// remove last word
tags.pop();
// array to string
tags = tags.join(' ');

感谢大家的帮助,特别是@ scott-markus和@ rory-mccrossan。

1 个答案:

答案 0 :(得分:-1)

要消除数组的最后一个元素,请使用 Array.pop() 并将数组元素连接到以空格分隔的字符串中,您必须将空格传递给.join()

逗号正在显示,因为您正在记录一个数组,并且为您自己插入逗号分隔数组项,读者 - 它们不是数组的实际部分。但是,如果您希望将单词作为字符串,只需将空格传递给.join()方法即可获得所需的输出。



var inputVal = document.getElementById("txtWords");

inputVal.addEventListener("blur", function(){

  tags = inputVal.value.split(' ');  // create tags array

  tags.pop();  // remove last word

  tags = tags.join(" ");  // array to string separated by spaces

  console.log(tags);
  
});

Type some words in the box and then hit TAB: <input type="text" id="txtWords">
&#13;
&#13;
&#13;