简体   繁体   中英

Pass/convert a php comma separated string to a js array due localstorage

I can't figure out how to pass/convert a php comma separated string to a javascript array due localstorage. I store:

...
$SelectedPlaces = "101,102,103";
...
<script>    
localStorage.setItem("SelectedPlaces", "<?php echo $SelectedPlaces; ?>");
</script>

I must retrieve later on in javascript array like:

var bookedSeats = [101,102,103];

but how to write the localStorage.getItem?

Just use String.split function with Number constructor(to convert substrings into numbers) when getting a certain "string" item from localStorage:

localStorage.setItem("SelectedPlaces", "<?php echo $SelectedPlaces; ?>");

var places = localStorage.getItem("SelectedPlaces").split(",").map(Number);

console.log(places);    // [101, 102, 103]

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