Konwertuj łańcuch z przecinkami na tablicę
Jak mogę przekonwertować łańcuch znaków na tablicę JavaScript?
Spójrz na kod:
var string = "0,1";
var array = [string];
alert(array[0]);
W tym przypadku, alert
wyskakuje 0,1
. Gdy jest to tablica, wyskakuje 0
, A gdy jest wywołana alert(array[1]);
, powinna wyskakiwać 1
.
Czy jest szansa na konwersję takiego łańcucha do tablicy JavaScript?
15 answers
Dla prostych członków tablicy można użyć JSON.parse
.
var array = JSON.parse("[" + string + "]");
To daje tablicę liczb.
[0, 1]
Jeśli użyjesz .split()
, skończysz z tablicą łańcuchów.
["0", "1"]
Pamiętaj, że JSON.parse
ograniczy Cię do obsługiwanych typów danych. Jeśli potrzebujesz wartości, takich jak undefined
lub funkcje, musisz użyć eval()
lub parsera JavaScript.
Jeśli chcesz użyć .split()
, ale chcesz również tablicy liczb, możesz użyć Array.prototype.map
, choć trzeba by go schować dla IE8 i niższych lub po prostu napisać tradycyjną pętlę.
var array = string.split(",").map(Number);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-07 15:19:58
Podziel na znak ,
;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-07 15:08:50
Można to łatwo osiągnąć w ES6 ;
Można przekonwertować ciągi znaków na tablice za pomocą tablicy .from ('string');
Array.from("01")
Będzie pocieszać.log
['0', '1']
Dokładnie tego szukasz.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-04 16:53:02
Jeśli łańcuch jest już w formacie listy, możesz użyć JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-05 19:27:55
Konwertuj wszystkie typy łańcuchów
var array = (new Function("return [" + str+ "];")());
Dlaczego powyżej najlepszych praktyk, spowodować jego accept string i objectstrings
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
Wynik w konsoli
Niektóre praktyki nie obsługują ciągów obiektów
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-28 05:16:34
Dla prostych członków tablicy, takich jak ten, możesz użyć JSON.parse.
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
var array = JSON.parse("[" + listValues + "]");
To daje tablicę liczb.
Teraz wartość zmiennej jest jak tablica.length=1
Wartość wyjściowa
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-10 03:51:32
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-17 13:59:06
Inną opcją używającą ES6 jest użycie składni Spread .
var convertedArray = [..."01234"];
var stringToConvert = "012";
var convertedArray = [...stringToConvert];
console.log(convertedArray);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-17 05:28:32
Użyj wbudowanej funkcji mapy z funkcją anonimową, TAK:
string.split(',').map(function(n) {return Number(n);});
[edytuj] oto jak go wykorzystać
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-09 21:54:31
Więcej przykładów "Wypróbuj sam" poniżej.
Definicja i użycie Metoda split() służy do podziału łańcucha znaków na tablicę podłańcuchów i zwraca nową tablicę.
Wskazówka: Jeśli jako separator używany jest pusty łańcuch ( "" ), łańcuch jest dzielony między każdym znakiem.
Uwaga: metoda split() nie zmienia oryginalnego ciągu znaków.
var res = str.split(",");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-16 07:13:59
Split (",") potrafi konwertować łańcuchy z przecinkami na tablicę łańcuchów, oto mój fragment kodu.
var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
var output = input.split(",");
console.log(output);
["Hybrid App", "Phone-Gap", "Apache Cordova", " HTML5", " JavaScript", "BootStrap", "JQuery", "css3", "Android Wear API"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-16 10:54:49
var i = "[{a:1,b:2}]",
j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
k = JSON.parse(j);
console.log(k)
// => deklarowanie wyrażenia regularnego
[a-zA-Z0-9] => dopasuj wszystkie a-z, A-Z, 0-9
(): => Grupuj wszystkie dopasowane elementy
$1 => łańcuch zastępczy odnosi się do pierwszej grupy dopasowania w wyrażeniu regularnym.
G = > global flag
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-26 05:02:24
Usuwam znaki ' [ ' ,'] 'i dokonuję podziału na', '
let array = stringObject.replace('[','').replace(']','').split(",").map(String);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-26 11:37:26
W ogólnym przypadku można użyć funkcji match.
const str = '1,2,3,4';
const strArr = str.match(/\d/g);
console.log(strArr[0])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-06 09:52:00
Dlaczego nie zamienisz ,
przecinka i split('')
takiego ciągu, który spowoduje ['0', '1']
, ponadto możesz zawinąć wynik w parseInt()
, aby przekształcić element W Typ integer.
it('convert string to array', function () {
expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-01 10:28:02