[英]Javascript: Remove last occurence of comma in span tag
I want to append object keys to span tag with class result and separate them with comma. 我想附加对象键以跨类结果标记并用逗号分隔它们。 But I can't remove last occurence of comma in text.
但是我无法删除文本中最后出现的逗号。
Result: <span class="result"></span>
Javascript: 使用Javascript:
for (key in obj) {
$(".result").append(key + ",");
}
So, for example, instead of 1,2,3, it must be 1,2,3 因此,例如,它必须是1,2,3,而不是1,2,3
You may use the "join" method in order to combine array elements with separators between them like so: 您可以使用“ join”方法来组合数组元素和它们之间的分隔符,如下所示:
var sample = ["1", "2", "3"];
console.log(sample.join(","));
//outputs: 1,2,3
It does not work on object properties though, so you have to use Object.keys() in order to convert your object into an array of its properties (supported in most browsers). 但是,它不适用于对象属性,因此必须使用Object.keys()才能将对象转换为其属性的数组(大多数浏览器都支持)。
$(".result").append(Object.keys(obj).join(","));
Do it like this 像这样做
var str = "1,2,3,"
str = str.slice(0,-1)
console.log(str) //"1,2,3"
For your SPAN
I did this. 对于您的
SPAN
我这样做了。
$('.result').text($('.result').text().slice(0,-1))
Try solution in fiddle join() function of array comes in real handy 在数组的小提琴 join()函数中尝试解决方案非常方便
// if array
var ele = ["1", "2", "3"]
$(".result").append(ele.join(","));
// if object
var ele1 = { "a": 1, "b" :2, "c" : 3}
var value = $.map(ele1, function(k, v) { return k;}).join(",")
$(".result1").append(value)
You can also use the array methods: 您还可以使用数组方法:
var test = "a,b,c,,,";
var test1 = test.split(",");
while (!test1[test1.length-1]) {
test1.pop();
}
console.log(test1);
test = test1.join(",");
console.log(test);
I would do, instead: 我会改为:
var results = (Object.keys(obj)).join(",");
$(".result").append(results);
Far more simpler. 简单得多。 More efficient ;) If you do an append in a loop, the page will be redrawn every time you add a key.
效率更高;)如果您在循环中执行追加操作,则每次添加键时都会重新绘制页面。 That's slow.
太慢了 Plus, with
Object.keys(obj)
( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys ) you get an array with all the keys of the object, and you only need to join all elements in a string, separating it with a comma. 另外,使用
Object.keys(obj)
( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys ),您将获得一个包含对象所有键的数组,并且您只需要将所有元素连接到字符串中,并用逗号将其分隔开即可。 So more concise, no? 如此简洁,不是吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.