简体   繁体   中英

How to remove last comma of a javascript array

I've found lots of answers on how to remove last comma of javascript string and so, but I nowhere managed to find a solution for the following problem:

var columns = new Array("datum","viz1","viz2","gaz","aram_nappali",);

That's my array, and I want to remove the last comma, because they are generated via PHP if statements.

I tried the following but with no success:

columns = columns.substring(1, s.length - 1);

Anyone a simple solution?

Thanks in advance

var columns = ["datum","viz1","viz2","gaz","aram_nappali",];
var a = columns.toString();
//a will be "datum,viz1,viz2,gaz,aram_nappali"

Don't use new Array() , it does not do what you think it does (thanks to behaving differently depending on how many arguments you supply ). JavaScript has an array literal that you should be using instead (regardless of whether you write the JS by hand or generated it in a conversion step):

// in JavaScript:
var columns = ["datum","viz1","viz2","gaz","aram_nappali"];

And, if your JS is generated through PHP, then the solution here is to make sure you're using PHP correctly, by making it generate the proper JS source code:

// in PHP:
$varlist = array("datum","viz1","viz2","gaz","aram_nappali");

...

// use [implode] to convert your array to joined string:
$jscode = 'var columns = "' . implode('","', $varlist) . '"];';

If you want a string version of a comma-separated list (or "anything-separated" list), you use implode to make that happen.

You should really fix the PHP output, you can also do this trick as simple arrays ignore commas at the end

var columns = ["datum","viz1","viz2","gaz","aram_nappali",,,];
var test = new Array(columns.join());
console.log(test);

只需在创建数组后立即删除数组中的最后一项:

columns.splice((columns.length -1), 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM