Konwertuj tablicę javascript na ciąg znaków
Próbuję iterować nad listą "wartość" i przekonwertować ją na ciąg znaków. Oto kod:
var blkstr = $.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
alert(str);
return str;
}).get().join(", ");
Funkcja Alert() działa poprawnie i wyświetla właściwą wartość. Ale jakoś jquery .funkcja get () nie otrzymuje właściwego rodzaju obiektu i nie powiedzie się. Co robię źle?
15 answers
Jeśli value
jest tablicą asocjacyjną, taki kod będzie działał poprawnie:
var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
(wyjście pojawi się w konsoli dev)
Jak wspomniał Felix, each()
jest tylko iteracją tablicy, nic więcej.
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-10-22 22:00:25
Konwersja z tablicy na ciąg jest tak prosta !
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""
That ' s it Now A is a 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
2011-07-21 13:07:23
Możesz użyć .toString()
, aby połączyć tablicę z przecinkiem.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Lub ustaw separator za pomocą array.join('; '); // result: a; b; c
.
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
2014-02-19 20:38:04
Nie wiem, czy tego chciałeś, ale
var arr = [A, B, C];
var arrString = arr.join(", ");
Daje to następujące wyjście:
A, B, C
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-04-19 09:31:47
Cztery metody konwersji tablicy na łańcuch znaków.
Wymuszanie na łańcuchu
var arr = ['a', 'b', 'c'] + []; // "a,b,c"
var arr = ['a', 'b', 'c'] + ''; // "a,b,c"
Wywołanie .toString()
var arr = ['a', 'b', 'c'].toString(); // "a,b,c"
Jawne łączenie za pomocą .join()
var arr = ['a', 'b', 'c'].join(); // "a,b,c" (Defaults to ',' seperator)
var arr = ['a', 'b', 'c'].join(','); // "a,b,c"
Możesz użyć innych separatorów, na przykład ', '
var arr = ['a', 'b', 'c'].join(', '); // "a, b, c"
Za pomocą JSON.stringify()
Jest to czystsze, ponieważ cytuje łańcuchy wewnątrz tablicy i prawidłowo obsługuje zagnieżdżone tablice.
var arr = JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
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-08-10 20:18:53
jQuery.each
po prostu zapętla tablicę, nie robi nic z wartością zwracaną∆. Szukasz jQuery.map
(myślę również, że get()
jest zbędne, ponieważ nie masz do czynienia z obiektami jQuery):
var blkstr = $.map(value, function(val,index) {
var str = index + ":" + val;
return str;
}).join(", ");
DEMO
Ale po co w ogóle używać jQuery w tym przypadku? map
wprowadza tylko niepotrzebne wywołanie funkcji dla każdego elementu.
var values = [];
for(var i = 0, l = value.length; i < l; i++) {
values.push(i + ':' + value[i]);
}
// or if you actually have an object:
for(var id in value) {
if(value.hasOwnProperty(id)) {
values.push(id + ':' + value[id]);
}
}
var blkstr = values.join(', ');
∆: używa tylko wartości zwracanej, czy powinna kontynuować pętlę nad żywioły czy nie. Zwrócenie wartości "falsy" zatrzyma pętlę.
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
2011-03-13 13:04:06
Użyj join()
i separatora.
Przykład roboczy
var arr = ['a', 'b', 'c', 1, 2, '3'];
// using toString method
var rslt = arr.toString();
console.log(rslt);
// using join method. With a separator '-'
rslt = arr.join('-');
console.log(rslt);
// using join method. without a separator
rslt = arr.join('');
console.log(rslt);
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
2019-10-17 06:27:26
To moja funkcja, Konwertuj obiekt lub tablicę na json
function obj2json(_data){
str = '{ ';
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += "'" + i + "':" + obj2arr(v) ;
else if ($.type(v)== 'array')
str += "'" + i + "':" + obj2arr(v) ;
else{
str += "'" + i + "':'" + v + "'";
}
});
return str+= '}';
}
I just edit to v0.2^.^
function obj2json(_data){
str = (($.type(_data)== 'array')?'[ ': '{ ');
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += '"' + i + '":' + obj2json(v) ;
else if ($.type(v)== 'array')
str += '"' + i + '":' + obj2json(v) ;
else{
if($.type(_data)== 'array')
str += '"' + v + '"';
else
str += '"' + i + '":"' + v + '"';
}
});
return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
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-10-04 00:45:45
var arr = new Array();
var blkstr = $.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
return arr;
}).join(', ');
console.log(blkstr);
Lub
var arr = new Array();
$.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
});
console.log(arr.join(', '));
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
2011-03-13 12:57:28
I needed a array to become a String rappresentation of an array I mean I needed that
var a = ['a','b','c'];
//became a "real" array string-like to pass on query params so was easy to do:
JSON.stringify(a); //-->"['a','b','c']"
Może komuś się przyda:)
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-04-19 08:26:01
Konwersja tablicy na łańcuch GET param, który może być dołączony do adresu url, może być wykonana w następujący sposób
function encodeGet(array){
return getParams = $.map(array , function(val,index) {
var str = index + "=" + escape(val);
return str;
}).join("&");
}
Wywołaj tę funkcję jako
var getStr = encodeGet({
search: $('input[name="search"]').val(),
location: $('input[name="location"]').val(),
dod: $('input[name="dod"]').val(),
type: $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;
Które przekieruje użytkownika do/site / search? strona z parametrami get przedstawionymi w tablicy podanej do encodeGet.
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-03-10 20:59:53
Nie należy mylić tablic z listami.
To jest lista: {...}
. Nie ma długości ani innych właściwości tablicy.
To jest tablica: [...]
. Można używać funkcji tablicowych, metod i tak, jak ktoś tu zasugerował: someArray.toString()
;
someObj.toString();
nie będzie działać na innych typach obiektów, takich jak listy.
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
2020-12-04 09:00:42
Oto przykład użycia funkcji podkreślenia.
var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");
Ostatnim wyjściem będzie "Moe, larry, curly"
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-03-02 10:58:29
/ align = "left" / prototyp.toString()
Metoda toString () zwraca łańcuch reprezentujący podaną tablicę i jej elementy.
var months = ["Jan", "Feb", "Mar", "Apr"]; months.toString(); // "Jan,Feb,Mar,Apr"
Składnia
arr.toString()
Return value
Łańcuch reprezentujący elementy tablicy.
więcej informacji :
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
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
2020-12-05 06:10:45
Możemy użyć funkcji join () aby utworzyć łańcuch z tablicy, a jako parametr funkcji join nadajemy mu " pusty znak.
var newStr =mArray.join('');
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
2020-12-18 20:41:13